> For the complete documentation index, see [llms.txt](https://ayakaleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ayakaleaf-pro.ayaka.space/latex/zh-cn/te-ding-ling-yu/08-pgfplots-package.md).

# Pgfplots 宏包

## 引言

该 `pgfplots` 基于……的包 [`TikZ`](/latex/zh-cn/tu-xing-he-biao-ge/05-tikz-package.md)，是一个功能强大的可视化工具，非常适合创建科学/技术图形。其基本思想是：你提供输入数据/公式，而 `pgfplots` 负责其余部分。

### 文档导言区

要使用 `pgfplots` 要在文档中添加该包，请在导言区加入以下一行：

`\usepackage{pgfplots}`

你还可以在文档导言区配置 `pgfplots` 的行为。例如，要更改每个图的大小并保证向后兼容性（推荐），添加下一行：

`\pgfplotsset{width=10cm,compat=1.9}`

这会将每个 `pgfplot` 图形大小改为 10 厘米，这个尺寸很大；你可以使用不同单位（pt、mm、in）。 *compat* 参数用于让代码在 1.9 或更高版本的包上运行。

### 编译时间（简要背景）

当最初的 TeX 引擎被构想/编写出来时，也就是 40 多年前，它并不是为……而设计的 *直接* 生成图形——这些图形应当是由外部程序（例如 MetaPost）创建并导入排版文档中的文件。pdfTeX 的出现——它在很大程度上基于原始 TeX 软件——带来了创建图形的能力 *直接* ，方法是使用 pdfTeX 新增的内置 TeX 语言命令（称为 *原语*）它们可以输出生成图形所需的 PDF 运算符/数据。pdfTeX 的创建促成了诸如 `TikZ`, `pgfplots` 等复杂 LaTeX 图形宏包的发展，这些宏包能够生成使用高级 LaTeX 命令编码的图形。

不过，在幕后，在 pdfTeX 引擎（以及其他引擎）的深处，这些高级 LaTeX 图形命令需要通过“转换”回低级 pdfTeX 引擎（原语）命令来处理，而这些命令才会实际生成（输出）创建最终图形所需的 PDF 运算符。对这些图形 LaTeX 命令的处理——原语的展开和执行——可能会耗费相当可观的时间。即使是一条高级 LaTeX 图形命令，连同其对应的数据，也可能需要重复执行 *许多* 低级 TeX 引擎（原语）命令。对于最终用户而言，包含多个 `pgfplots` 图形和/或非常复杂图形的文档，渲染（编译）可能会花费相当长的时间。

### 减少编译时间

要提高文档编译速度，你可以配置 `pgfplots` 包将图形导出为单独的 PDF 文件，然后再将它们导入文档：编译一次，然后重复使用这些图形。为此，请将下面的代码添加到导言区：

```
\usepgfplotslibrary{external}
\tikzexternalize
```

参见 [这篇帮助文章](/latex/zh-cn/wen-da/60-i-have-a-lot-of-tikz-matlab2tikz-or-pgfplots-figures-so-i-m-getting-a-compilation-timeout.-can-i.md) 了解如何在你的 Overleaf 项目中设置 tikz 外部化。

## 基本示例（同时将图形外部化）

```latex
\documentclass{article}
\usepackage[margin=0.25in]{geometry}
\usepackage{pgfplots}
\pgfplotsset{width=10cm,compat=1.9}

% We will externalize the figures
\usepgfplotslibrary{external}
\tikzexternalize

\begin{document}

第一个示例是并排绘制二维和三维数学表达式。

%Here begins the 2D plot
\begin{tikzpicture}
\begin{axis}
\addplot[color=red]{exp(x)};
\end{axis}
\end{tikzpicture}
%Here ends the 2D plot
\hskip 5pt
%Here begins the 3D plot
\begin{tikzpicture}
\begin{axis}
\addplot3[
    surf,
]
{exp(-x^2-y^2)*x};
\end{axis}
\end{tikzpicture}
%Here ends the 3D plot

\end{document}
```

[打开此 `pgfplots` Overleaf 中的示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+example+1\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.25in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%0A%25+We+will+externalize+the+figures%0A%5Cusepgfplotslibrary%7Bexternal%7D%0A%5Ctikzexternalize%0A%0A%5Cbegin%7Bdocument%7D%0A%0AFirst+example+is+2D+and+3D+math+expressions+plotted+side-by-side.%0A%0A%25Here+begins+the+2D+plot%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%0A%5Caddplot%5Bcolor%3Dred%5D%7Bexp%28x%29%7D%3B%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%25Here+ends+the+2D+plot%0A%5Chskip+5pt%0A%25Here+begins+the+3D+plot%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%0A%5Caddplot3%5B%0A++++surf%2C%0A%5D%0A%7Bexp%28-x%5E2-y%5E2%29%2Ax%7D%3B%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%25Here+ends+the+3D+plot%0A%0A%5Cend%7Bdocument%7D)

下图显示了上面代码生成的结果：

![Plgplotsex1OLV2.png](/files/b31e1ea043706ded2dda126b8778158b1a91f318)

### 代码说明

因为 `pgfplots` 基于 `tikz` 图形必须位于 `tikzpicture` 环境中。然后，环境声明 `\begin{axis}`, `\end{axis}` 将为图形设置正确的缩放——请查看 [参考指南](#reference-guide) 了解其他坐标轴环境。

要添加实际图形，请使用命令 `\addplot[color=red]{log(x)};` 。在方括号中， `[...]`，可以传入一些选项；这里，我们将 `颜色` 设置为 `red`。方括号是必需的，如果没有传入选项，就在方括号之间留一个空格。把要绘制的函数放在花括号中。务必记住，这条命令必须以分号（;）结尾。

要把第二个图放在第一个旁边，请声明一个新的 `tikzpicture` 环境。不要换行，而要留出一小段空白，在这种情况下 `\hskip 10pt` 将插入一个宽度为 10pt 的空白。

其余语法相同，除了 `\addplot3 [surf,]{exp(-x^2-y^2)*x};`。这将添加一个 3D 图，而选项 `surf` 在方括号中表示这是一个曲面图。要绘制的函数必须放在花括号内。同样，不要忘记在命令末尾加上分号（;）。

**注意**：建议采用良好做法对代码进行缩进——见上面示例中的第二个图——并在传递给 `\addplot`的每个选项末尾添加逗号（,）。这样代码更易读，如果需要，也更容易添加更多选项。

## 二维图形

`pgfplots`的二维绘图功能非常强大——你可以根据需求自定义图形。不过，默认选项通常已经能产生很好的效果，所以你所需要做的只是提供数据，而 LaTeX 会完成其余工作。

### 绘制数学表达式

下面是一个示例：

```latex
\begin{tikzpicture}
\begin{axis}[
    axis lines = left,
    xlabel = \(x\),
    ylabel = {\(f(x)\)},
]
%Below the red parabola is defined
\addplot [
    domain=-10:10,
    samples=100,
    color=red,
]
{x^2 - 2*x - 1};
\addlegendentry{\(x^2 - 2x - 1\)}
%Here the blue parabola is defined
\addplot [
    domain=-10:10,
    samples=100,
    color=blue,
    ]
    {x^2 + 2*x + 1};
\addlegendentry{\(x^2 + 2x + 1\)}

\end{axis}
\end{tikzpicture}
```

[打开此 `pgfplots` Overleaf 中的示例。](https://www.overleaf.com/docs?engine=\&snip_name=pgfplots+example+2\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.25in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%5B%0A++++axis+lines+%3D+left%2C%0A++++xlabel+%3D+%5C%28x%5C%29%2C%0A++++ylabel+%3D+%7B%5C%28f%28x%29%5C%29%7D%2C%0A%5D%0A%25Below+the+red+parabola+is+defined%0A%5Caddplot+%5B%0A++++domain%3D-10%3A10%2C+%0A++++samples%3D100%2C+%0A++++color%3Dred%2C%0A%5D%0A%7Bx%5E2+-+2%2Ax+-+1%7D%3B%0A%5Caddlegendentry%7B%5C%28x%5E2+-+2x+-+1%5C%29%7D%0A%25Here+the+blue+parabola+is+defined%0A%5Caddplot+%5B%0A++++domain%3D-10%3A10%2C+%0A++++samples%3D100%2C+%0A++++color%3Dblue%2C%0A++++%5D%0A++++%7Bx%5E2+%2B+2%2Ax+%2B+1%7D%3B%0A%5Caddlegendentry%7B%5C%28x%5E2+%2B+2x+%2B+1%5C%29%7D%0A%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

这段代码的输出如下图所示——当你打开链接时，LaTeX 文档导言区会自动添加：

![Plgplotsex2.png](/files/d49e4122cb852293dbf8e3276df36dfaf75f174a)

#### 代码说明

让我们逐行分析这些新命令：

**axis lines = left。**

这会将坐标轴设置在图的左侧和底部，而不是默认的方框。更多自定义选项请参见参考指南。

**xlabel = (x) 和 ylabel = {(f(x))}。**

这些都是不言自明的参数名，它们可以让你给水平轴和垂直轴添加标签。注意 ylabel 的值位于花括号中，这些花括号告诉 pgfplots 如何将文本分组。xlabel 也可以加花括号。这对于那些可能让 pgfplots 感到困惑的复杂标签很有用。

**\addplot。**

这会向坐标轴添加一条曲线/图形，前文已经介绍了其基本用法。这个例子中有两个新参数。

**domain=-10:10。**

这定义了 x 值的范围。

**samples=100。**

确定 domain 所定义区间内的点数。samples 的值越大，得到的曲线越平滑，但渲染所需时间也越长。

**\addlegendentry{\\(x^2 - 2x - 1\\)}.**

这会添加图例，以标识函数 x^2 - 2x - 1。

要在图中再添加另一条曲线，只需写一个新的 `\addplot` 条目。

### 从数据绘图

科学研究往往会产生需要分析的数据。下面的示例展示了如何使用 *pgfplots*:

```latex
从数据绘图：

\begin{tikzpicture}
\begin{axis}[
    title={Temperature dependence of CuSO\(_4\cdot\)5H\(_2\)O solubility},
    xlabel={Temperature [\textcelsius]},
    ylabel={Solubility [g per 100 g water]},
    xmin=0, xmax=100,
    ymin=0, ymax=120,
    xtick={0,20,40,60,80,100},
    ytick={0,20,40,60,80,100,120},
    legend pos=north west,
    ymajorgrids=true,
    grid style=dashed,
]

\addplot[
    color=blue,
    mark=square,
    ]
    coordinates {
    (0,23.1)(10,27.5)(20,32)(30,37.8)(40,44.6)(60,61.8)(80,83.8)(100,114)
    };
    \legend{CuSO\(_4\cdot\)5H\(_2\)O}

\end{axis}
\end{tikzpicture}
```

[打开此 `pgfplots` Overleaf 中的示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+example+3\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Btextcomp%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0APlotting+from+data%3A%0A%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%5B%0A++++title%3D%7BTemperature+dependence+of+CuSO%5C%28_4%5Ccdot%5C%295H%5C%28_2%5C%29O+solubility%7D%2C%0A++++xlabel%3D%7BTemperature+%5B%5Ctextcelsius%5D%7D%2C%0A++++ylabel%3D%7BSolubility+%5Bg+per+100+g+water%5D%7D%2C%0A++++xmin%3D0%2C+xmax%3D100%2C%0A++++ymin%3D0%2C+ymax%3D120%2C%0A++++xtick%3D%7B0%2C20%2C40%2C60%2C80%2C100%7D%2C%0A++++ytick%3D%7B0%2C20%2C40%2C60%2C80%2C100%2C120%7D%2C%0A++++legend+pos%3Dnorth+west%2C%0A++++ymajorgrids%3Dtrue%2C%0A++++grid+style%3Ddashed%2C%0A%5D%0A%0A%5Caddplot%5B%0A++++color%3Dblue%2C%0A++++mark%3Dsquare%2C%0A++++%5D%0A++++coordinates+%7B%0A++++%280%2C23.1%29%2810%2C27.5%29%2820%2C32%29%2830%2C37.8%29%2840%2C44.6%29%2860%2C61.8%29%2880%2C83.8%29%28100%2C114%29%0A++++%7D%3B%0A++++%5Clegend%7BCuSO%5C%28_4%5Ccdot%5C%295H%5C%28_2%5C%29O%7D%0A++++%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

这段代码的输出如下图所示——当你打开链接时，LaTeX 文档导言区会自动添加：

![Plgplotsex3.png](/files/3ba26fe95178c90c3e5c87d89d8f66377547c7ff)

#### 代码说明

这里有一些新的命令和参数：

**title={Temperature dependence of CuSO(\_4\cdot)5H(\_2)O solubility}.**

顾名思义，它为图形指定一个标题。标题会显示在图的上方。

**xmin=0, xmax=100, ymin=0, ymax=120。**

x 轴和 y 轴的最小值与最大值边界。

**xtick={0,20,40,60,80,100}, ytick={0,20,40,60,80,100,120}。**

标记放置的位置。如果为空，则刻度会自动设置。

**legend pos=north west。**

图例框的位置。更多选项请参见参考指南。

**ymajorgrids=true。**

这会启用/禁用 y 轴刻度位置的网格线。使用 xmajorgrids 可在 x 轴上启用网格线。

**grid style=dashed。**

不言自明。用于显示虚线网格。

**mark=square。**

这会在 coordinates 数组中的每个点上绘制一个方形标记。每个标记都会用直线与下一个标记连接。

**coordinates {(0,23.1)(10,27.5)(20,32)...}**

要绘制的点坐标。这就是你想以图形方式分析的数据。

如果数据在文件中，而大多数时候都是这样；那么不要使用命令 `\addplot` 和 `coordinates` ，而应使用 `\addplot table {file_with_the_data.dat}`，其余选项在此环境中同样有效。

### 散点图

散点图用于通过某种标记来表示信息，常用于统计回归计算。在这个例子中，我们将使用名为 `scattered_example.dat`的数据文件创建一个散点图，其中的数据如下：

```
GPA  ma  ve  co   un
3.45 643 589 3.76 3.52
2.78 558 512 2.87 2.91
2.52 583 503 2.54 2.4
3.67 685 602 3.83 3.47
3.24 592 538 3.29 3.47
2.1 562 486 2.64 2.37
...
```

我们的散点图使用数据的前两列：

```latex
\begin{tikzpicture}
\begin{axis}[
    enlargelimits=false,
]
\addplot+[
    only marks,
    scatter,
    mark=halfcircle*,
    mark size=2.9pt]
table[meta=ma]
{scattered_example.dat};
\end{axis}
\end{tikzpicture}
```

![Scattered.png](/files/ab1a7fb050198c53c4aa7397524e512aecada821)

[在 Overleaf 中打开一个散点图项目示例（包含数据文件 `scattered_example.dat`).](https://www.overleaf.com/project/new/template/20099?id=68399290\&templateName=Scatter+plot+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

#### 代码说明

传递给 `axis` 和 `和` 环境的参数也可以用于数据图中，除了 `scatter`。下面是代码说明：

**enlarge limits=false**

这会缩小坐标轴，使最大值和最小值对应的点位于图的边缘。

**only marks**

非常明确，会在每个点上放置一个标记。

**scatter**

使用 scatter 时，点会根据某个值着色，颜色由下面解释的 meta 参数给出。

**mark=halfcircle**\*

每个点使用的标记类型，请查参考指南中的可选值列表。

**mark size=2.9pt**

每个标记的大小，可以使用不同单位。

**table\[meta=ma]{scattered\_example.dat};**

这里 table 命令告诉 latex，要绘制的数据在文件中。meta=ma 参数用于选择决定每个点颜色的列。花括号中是数据文件名。

### 条形图

条形图（也称条形图表和条形绘图）用于展示收集到的数据，主要是某类总体的统计数据。 `pgfplots` 中的条形图具有很高的可配置性，但这里我们展示一个简单示例：

```latex
\begin{tikzpicture}
\begin{axis}[
	x tick label style={
		/pgf/number format/1000 sep=},
	ylabel=Year,
	enlargelimits=0.05,
	legend style={at={(0.5,-0.1)},
	anchor=north,legend columns=-1},
	ybar interval=0.7,
]
\addplot
	coordinates {(2012,408184) (2011,408348)
		 (2010,414870) (2009,412156)};
\addplot
	coordinates {(2012,388950) (2011,393007)
		(2010,398449) (2009,395972)};
\legend{Men,Women}
\end{axis}
\end{tikzpicture}
```

[打开此 `pgfplots` Overleaf 中的条形图代码示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+bar+chart+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Btextcomp%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%5B%0A%09x+tick+label+style%3D%7B%0A%09%09%2Fpgf%2Fnumber+format%2F1000+sep%3D%7D%2C%0A%09ylabel%3DYear%2C%0A%09enlargelimits%3D0.05%2C%0A%09legend+style%3D%7Bat%3D%7B%280.5%2C-0.1%29%7D%2C%0A%09anchor%3Dnorth%2Clegend+columns%3D-1%7D%2C%0A%09ybar+interval%3D0.7%2C%0A%5D%0A%5Caddplot+%0A%09coordinates+%7B%282012%2C408184%29+%282011%2C408348%29%0A%09%09+%282010%2C414870%29+%282009%2C412156%29%7D%3B%0A%5Caddplot+%0A%09coordinates+%7B%282012%2C388950%29+%282011%2C393007%29+%0A%09%09%282010%2C398449%29+%282009%2C395972%29%7D%3B%0A%5Clegend%7BMen%2CWomen%7D%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

这段代码的输出如下图所示——当你打开链接时，LaTeX 文档导言区会自动添加：

![Barchartsexample.png](/files/59a9fe46feb0f8836c3b14ead13ebe4ab4c780f8)

#### 代码说明

图形以（[前面已解释的](#introduction)） `tikzpicture` 和 `axis` 环境声明开始，但 `axis` 声明有许多新参数：

**x tick label style={/pgf/number format/1000 sep=}**

这段代码为该图定义了一个完整的样式。使用这种样式，你可以在这个 axis 环境中加入多条 \addplot 命令，它们会自然地契合并很好地显示在一起，无需进一步调整（下面描述的 ybar 参数对此是必需的）。

**enlargelimits=0.05。**

在条形图中扩大边界是必要的，因为这类图通常需要在柱子上方留出一些额外空间，以便看起来更美观和/或添加标签。这里的 0.05 是相对于图的总高度而言的。

**legend style={at={(0.5,-0.2)}, anchor=north,legend columns=-1}**

同样，这在大多数情况下都很好用。必要时，将 -0.2 的值改掉，以便让图例更靠近/远离 x 轴。

**ybar interval=0.7,**

每个柱子的厚度。1 表示柱子彼此相邻、没有间隙；0 表示没有柱子，只有竖线。

该 `coordinates` 在这种图中用于确定柱子的基点及其高度。

y 轴上的标签最多显示 4 位数字。如果你处理的数字大于 9999 `pgfplots` 将使用与示例中相同的记法。

## 三维图形

`pgfplots` 具有你在绘图软件中所期望的三维绘图能力。

### 绘制数学表达式

这方面有一个简单示例，见 [引言](#introduction)，下面我们来做一个稍微复杂一些的：

```latex
\begin{tikzpicture}
\begin{axis}[
    title=Example using the mesh parameter,
    hide axis,
    colormap/cool,
]
\addplot3[
    mesh,
    samples=50,
    domain=-8:8,
]
{sin(deg(sqrt(x^2+y^2)))/sqrt(x^2+y^2)};
\addlegendentry{\(\frac{sin(r)}{r}\)}
\end{axis}
\end{tikzpicture}
```

[打开此 `pgfplots` Overleaf 中的三维示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+3D+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%5B%0A++++title%3DExample+using+the+mesh+parameter%2C%0A++++hide+axis%2C%0A++++colormap%2Fcool%2C%0A%5D%0A%5Caddplot3%5B%0A++++mesh%2C%0A++++samples%3D50%2C%0A++++domain%3D-8%3A8%2C%0A%5D%0A%7Bsin%28deg%28sqrt%28x%5E2%2By%5E2%29%29%29%2Fsqrt%28x%5E2%2By%5E2%29%7D%3B%0A%5Caddlegendentry%7B%5C%28%5Cfrac%7Bsin%28r%29%7D%7Br%7D%5C%29%7D%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

这段代码的输出如下图所示——当你打开链接时，LaTeX 文档导言区会自动添加：

![Pgfplots3dexample.png](/files/fe5a0cef157bf8528fb6075099447bfb09afcfcb)

#### 代码说明

这里的大多数命令之前都已经解释过了，但有 3 个新东西：

**hide axis**

这个 axis 环境中的选项不言自明，坐标轴不会显示。

**colormap/cool**

这是图中要使用的配色方案。更多配色方案请查看参考指南。

**mesh**

这个选项也不言自明，另请参见入门示例中的 surf 参数。

**注意**：当处理三角函数时 `pgfplots` 默认使用度作为单位，如果角度是弧度（如本例）你就必须使用 `deg` 函数将其转换为度。

### 等高线图

在 `pgfplots` 中，可以绘制等高线图，但数据必须由外部程序预先计算。我们来看一个例子：

```latex
\begin{tikzpicture}
\begin{axis}
[
    title={Contour plot, view from top},
    view={0}{90}
]
\addplot3[
    contour gnuplot={levels={0.8, 0.4, 0.2, -0.2}}
]
{sin(deg(sqrt(x^2+y^2)))/sqrt(x^2+y^2)};
\end{axis}
\end{tikzpicture}
```

[打开此 `pgfplots` Overleaf 中的等高线图示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+contour+plot+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%0A%5B%0A++++title%3D%7BContour+plot%2C+view+from+top%7D%2C%0A++++view%3D%7B0%7D%7B90%7D%0A%5D%0A%5Caddplot3%5B%0A++++contour+gnuplot%3D%7Blevels%3D%7B0.8%2C+0.4%2C+0.2%2C+-0.2%7D%7D%0A%5D%0A%7Bsin%28deg%28sqrt%28x%5E2%2By%5E2%29%29%29%2Fsqrt%28x%5E2%2By%5E2%29%7D%3B%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%0A%5Cend%7Bdocument%7D)

这段代码的输出如下图所示——当你打开链接时，LaTeX 文档导言区会自动添加：

![Contourplotexample.png](/files/3e5fdf9c346da98f2d1e8a870608de26456057c3)

#### 代码说明

这是上一节所用同一方程的一些等高线图。值 `标题` 参数位于花括号中，因为它包含逗号，所以我们使用分组括号，以避免与传递给 `\begin{axis}` 声明的其他参数混淆。这里有两个新命令：

**view={0}{90}**

这会更改图的视角。该参数传递给 axis 环境，这意味着它可用于任何其他类型的 3D 图。第一个值是在 z 轴周围旋转的角度（度）；第二个值是绕 x 轴旋转视角。在本例中，当我们将绕 z 轴 0° 旋转与绕 x 轴 90° 旋转结合起来时，我们得到的是从顶部观察图形的视角。

**contour gnuplot={levels={0.8, 0.4, 0.2, -0.2}}**

这行代码做了两件事：首先，它告诉 LaTeX 使用外部软件 gnuplot 来计算等高线；这在 Overleaf 中运行良好，但如果你想在本地 LaTeX 安装中使用该命令，则必须先安装 gnuplot（在这种情况下，matlab 也可以工作，只需在命令中用 matlab 代替 gnuplot 即可）。其次，子参数 levels 是一个海拔层级值列表，用于计算等高线。

### 绘制三维曲面

要在三维曲面中绘制一组数据，我们只需要每个点的坐标。这些坐标可以是一组无序数据，或者在本例中，是一个矩阵：

```latex
\begin{tikzpicture}
\begin{axis}
\addplot3[
    surf,
]
coordinates {
(0,0,0) (0,1,0) (0,2,0)

(1,0,0) (1,1,0.6) (1,2,0.7)

(2,0,0) (2,1,0.7) (2,2,1.8)
};
\end{axis}
\end{tikzpicture}
```

[打开此 `pgfplots` Overleaf 中的三维曲面示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=plotting+a+surface+from+data+with+pgfplots\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%0A%5Caddplot3%5B%0A++++surf%2C%0A%5D+%0Acoordinates+%7B%0A%280%2C0%2C0%29+%280%2C1%2C0%29+%280%2C2%2C0%29%0A%0A%281%2C0%2C0%29+%281%2C1%2C0.6%29+%281%2C2%2C0.7%29%0A%0A%282%2C0%2C0%29+%282%2C1%2C0.7%29+%282%2C2%2C1.8%29%0A%7D%3B%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%0A%5Cend%7Bdocument%7D)

这段代码的输出如下图所示——当你打开链接时，LaTeX 文档导言区会自动添加：

![3dsurfacedata.png](/files/183f4d57ea4f04a19841ec257edc7d3c71892757)

#### 数据说明

传入到 `coordinates` 参数的点被视为包含在一个 3 × 3 矩阵中，每一行矩阵之间用空行分隔。

本文中所有适用于 3D 图的选项也同样适用于数据曲面。

### 参数图

参数图的语法略有不同。我们来看一个例子：

```latex
\begin{tikzpicture}
\begin{axis}
    [
    view={60}{30},
    ]
\addplot3[
    domain=0:5*pi,
    samples = 60,
    samples y=0,
]
({sin(deg(x))},
{cos(deg(x))},
{x});
\end{axis}
\end{tikzpicture}
```

[打开此 `pgfplots` Overleaf 中的参数图示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+parametric+plot+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%0A++++%5B%0A++++view%3D%7B60%7D%7B30%7D%2C%0A++++%5D%0A%5Caddplot3%5B%0A++++domain%3D0%3A5%2Api%2C%0A++++samples+%3D+60%2C%0A++++samples+y%3D0%2C%0A%5D%0A%28%7Bsin%28deg%28x%29%29%7D%2C%0A%7Bcos%28deg%28x%29%29%7D%2C%0A%7Bx%7D%29%3B%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

这段代码的输出如下图所示——当你打开链接时，LaTeX 文档导言区会自动添加：

![Parametricplot.png](/files/bcca902f49350d2ae080bc6d120591ed0db16fec)

#### 代码说明

这个例子中只有两个新东西：首先是 `samples y=0` 以防止 `pgfplots` 将螺旋线的两个端点连接起来；其次是将要绘制的函数传递给 `addplot3` 环境的方式。每个参数函数都被分组在花括号中，并且三个参数用括号分隔。

## 参考指南

| 命令/选项/环境         | 说明                                     | 可能的取值                                                                                                                                                                                                                                                                                                           |
| ---------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **axis**         | 具有线性缩放的普通图形                            |                                                                                                                                                                                                                                                                                                                 |
| **semilogxaxis** | x 轴为对数缩放，y 轴为普通缩放                      |                                                                                                                                                                                                                                                                                                                 |
| **semilogyaxis** | y 轴为对数缩放，x 轴为普通缩放                      |                                                                                                                                                                                                                                                                                                                 |
| **loglogaxis**   | x 轴和 y 轴都为对数缩放                         |                                                                                                                                                                                                                                                                                                                 |
| **axis lines**   | 更改坐标轴的绘制方式。默认值是 '*盒子*                  | box, left, middle, center, right, none                                                                                                                                                                                                                                                                          |
| **legend pos**   | 图例框的位置                                 | south west, south east, north west, north east, outer north east                                                                                                                                                                                                                                                |
| **mark**         | 数据绘图中使用的标记类型。当使用单字符时，该字符的外观会与实际标记非常相似。 | \*, x , +, \|, o, asterisk, star, 10-pointed star, oplus, oplus\*, otimes, otimes\*, square, square\*, triangle, triangle\*, diamond, halfdiamond\*, halfsquare\*, right\*, left\*, Mercedes star, Mercedes star flipped, halfcircle, halfcircle\*, pentagon, pentagon\*, cubes. (cubes only work on 3d plots). |
| **colormap**     | 绘图中使用的配色方案，可以自定义，但也有一些预定义的 colormap。   | hot, hot2, jet, blackwhite, bluered, cool, greenyellow, redyellow, violet.                                                                                                                                                                                                                                      |

## 进一步阅读

更多信息请参见：

* [在 LaTeX 中使用颜色](/latex/zh-cn/ge-shi-hua/13-using-colors-in-latex.md)
* [TikZ 宏包](/latex/zh-cn/tu-xing-he-biao-ge/05-tikz-package.md)
* [外部化 pgfplots 和 tikzpictures](/latex/zh-cn/wen-da/60-i-have-a-lot-of-tikz-matlab2tikz-or-pgfplots-figures-so-i-m-getting-a-compilation-timeout.-can-i.md)
* [插入图片](/latex/zh-cn/geng-duo-zhu-ti/27-inserting-images.md)
* [表格和图形列表](/latex/zh-cn/tu-xing-he-biao-ge/03-lists-of-tables-and-figures.md)
* [图片和表格的定位](/latex/zh-cn/tu-xing-he-biao-ge/02-positioning-images-and-tables.md)
* [在 LaTeX 中直接绘制图表](/latex/zh-cn/tu-xing-he-biao-ge/04-picture-environment.md)
* [该 **pgfplots** 包文档](http://mirrors.ctan.org/graphics/pgf/contrib/pgfplots/doc/pgfplots.pdf).
* [TikZ 和 PGF 宏包：3.0.0 版手册](http://mirror.utexas.edu/ctan/graphics/pgf/base/doc/pgfmanual.pdf)
* [TeXample.net 上的 TikZ 和 PGF 示例](http://www.texample.net/tikz/examples/all/)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ayakaleaf-pro.ayaka.space/latex/zh-cn/te-ding-ling-yu/08-pgfplots-package.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
