> For the complete documentation index, see [llms.txt](https://overleaf-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://overleaf-pro.ayaka.space/latex/zh-cn/te-ding-ling-yu/08-pgfplots-package.md).

# Pgfplots 宏包

## 引言

该 `pgfplots` 基于……的 package [`TikZ`](/latex/zh-cn/tu-biao-he-biao-ge/05-tikz-package.md)，是一个强大的可视化工具，非常适合创建科学/技术图形。基本思路是你提供输入数据/公式，而 `pgfplots` 其余的工作都由它完成。

### 文档导言区

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

`\usepackage{pgfplots}`

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

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

这会改变每个 `pgfplot` 图的大小为 10 厘米，这非常大；你可以使用不同的单位（pt、mm、in）。 *compat* 参数用于使代码在 package 1.9 或更高版本上工作。

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

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

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

### 减少编译时间

要提高文档编译速度，你可以配置 `pgfplots` package，将图形导出为单独的 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}

% 我们将把图形外部化
\usepgfplotslibrary{external}
\tikzexternalize

\begin{document}

第一个示例是并排绘制的 2D 和 3D 数学表达式。

%这里开始 2D 绘图
\begin{tikzpicture}
\begin{axis}
\addplot[color=red]{exp(x)};
\end{axis}
\end{tikzpicture}
%这里结束 2D 绘图
\hskip 5pt
%这里开始 3D 绘图
\begin{tikzpicture}
\begin{axis}
\addplot3[
    surf,
]
{exp(-x^2-y^2)*x};
\end{axis}
\end{tikzpicture}
%这里结束 3D 绘图

\end{document}
```

[在 Overleaf 中打开此 `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};`。这会添加一个 3dplot，而选项 `surf` 在方括号中表示这是一个曲面图。要绘制的函数必须放在花括号中。同样，不要忘记在命令末尾加上分号（;）。

**注意**：建议将代码缩进作为良好实践——请参见上面示例中的第二个图——并在传递给 `\addplot`的每个选项末尾添加一个逗号（,）。这样代码更易读，也更便于在需要时添加更多选项。

## 2D 图

`pgfplots`’ 的 2D 绘图功能非常强大——你可以根据需要自定义图形。不过，默认选项通常已经能得到很好的结果，所以你只需要输入数据，LaTeX 会完成其余工作。

### 绘制数学表达式

下面是一个示例：

```latex
\begin{tikzpicture}
\begin{axis}[
    axis lines = left,
    xlabel = \(x\),
    ylabel = {\(f(x)\)},
]
%下面定义红色抛物线
\addplot [
    domain=-10:10,
    samples=100,
    color=red,
]
{x^2 - 2*x - 1};
\addlegendentry{\(x^2 - 2x - 1\)}
%这里定义蓝色抛物线
\addplot [
    domain=-10:10,
    samples=100,
    color=blue,
    ]
    {x^2 + 2*x + 1};
\addlegendentry{\(x^2 + 2x + 1\)}

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

[在 Overleaf 中打开此 `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={CuSO\(_4\cdot\)5H\(_2\)O 溶解度对温度的依赖性},
    xlabel={温度 [\textcelsius]},
    ylabel={溶解度 [每 100 g 水中的 g 数]},
    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}
```

[在 Overleaf 中打开此 `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={CuSO(\_4\cdot)5H(\_2)O 溶解度对温度的依赖性}。**

正如你所料，这会为图形指定一个标题。标题将显示在图的上方。

**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 {(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` 和 `addplot` 环境的参数也可以用于数据图中，除了 `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 参数以选择决定每个点颜色的列。花括号中是数据文件的名称。

### 条形图

条形图（也称为 bar charts 和 bar plots）用于显示收集到的数据，主要是关于某类人群的统计数据。中的条形图 `pgfplots` 高度可配置，但这里我们展示一个简单示例：

```latex
\begin{tikzpicture}
\begin{axis}[
	x tick label style={
		/pgf/number format/1000 sep=},
	ylabel=年份,
	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}
```

[在 Overleaf 中打开此 `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` 将使用与示例中相同的表示法。

## 3D 图

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

### 绘制数学表达式

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

```latex
\begin{tikzpicture}
\begin{axis}[
    title=使用 mesh 参数的示例,
    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}
```

[在 Overleaf 中打开此 `pgfplots` Overleaf 中的 3D 示例。](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={等高线图，俯视图},
    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}
```

[在 Overleaf 中打开此 `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)

#### 代码说明

这是前一节所用同一方程的一些等高线图。 `title` 参数位于花括号内，因为它包含逗号，所以我们使用分组括号来避免与传递给 `\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 也可以，在这种情况下，命令中将 gnuplot 改为 matlab 即可）。其次，子参数 levels 是一个列表，列出要计算等高线的高度值。

### 从数据绘制曲面

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

```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}
```

[在 Overleaf 中打开此 `pgfplots` Overleaf 中的 3D 曲面示例。](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}
```

[在 Overleaf 中打开此 `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-biao-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-biao-he-biao-ge/03-lists-of-tables-and-figures.md)
* [图片和表格的位置](/latex/zh-cn/tu-biao-he-biao-ge/02-positioning-images-and-tables.md)
* [在 LaTeX 中直接绘制图表](/latex/zh-cn/tu-biao-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://overleaf-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.
