关于 pgfplots
pgfplots 是 LaTeX 绘图软件包;此技能提供实用参考,涵盖图表类型、坐标轴、样式、数据文件及常见问题排查,适合在 LaTeX 中制作图形。
主要功能
- 01折线图、散点图与柱状图
- 02统计图与 3D 图
- 03坐标轴和图例自定义
- 04读取数据文件绘图
- 05常见错误排查
适用场景
- 01为 LaTeX 文档制作图表
- 02绘制 CSV 文件中的数值
- 03构建分组图或多坐标轴图
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ igbuend/ grimbard --skill pgfplots安装后在 Claude Code 中输入/pgfplots确认已加载。
详细介绍
pgfplots — 数据可视化与绘图
CTAN: https://ctan.org/pkg/pgfplots
手册: texdoc pgfplots
设置
\usepackage{pgfplots}
\pgfplotsset{compat=1.18} % ALWAYS set this — enables latest features
% Optional libraries
\usepgfplotslibrary{fillbetween, groupplots, statistics, colorbrewer, polar}
基本绘图
\begin{tikzpicture}
\begin{axis}[
xlabel={$x$},
ylabel={$f(x)$},
title={My Plot},
grid=major,
]
\addplot[blue, thick, domain=-3:3, samples=100] {x^2};
\addlegend{$x^2$}
\end{axis}
\end{tikzpicture}
坐标轴环境
| 环境 | 描述 |
|---|---|
axis | 标准线性坐标轴 |
semilogxaxis | x 轴采用对数刻度 |
semilogyaxis | y 轴采用对数刻度 |
loglogaxis | 两个坐标轴均采用对数刻度 |
polaraxis | 极坐标(需要 polar 库) |
坐标轴选项参考
| 选项 | 示例 | 描述 |
|---|---|---|
xlabel | xlabel={Time (s)} | X 轴标签 |
ylabel | ylabel={Voltage} | Y 轴标签 |
title | title={Results} | 图表标题 |
xmin/xmax | xmin=0, xmax=10 | 坐标轴范围 |
ymin/ymax | ymin=-1, ymax=1 | 坐标轴范围 |
domain | domain=0:2*pi | 默认绘图定义域 |
samples | samples=200 | 默认采样数 |
grid | grid=major | major、minor、both、none |
legend pos | legend pos=north west | 图例位置 |
width/height | width=10cm | 坐标轴尺寸 |
axis lines | axis lines=middle | box、left、middle、none |
enlargelimits | enlargelimits=0.1 | 扩展坐标轴范围 |
xtick | xtick={0,1,...,5} | 自定义刻度位置 |
xticklabels | xticklabels={A,B,C} | 自定义刻度标签 |
x tick label style | x tick label style={rotate=45} | 刻度标签格式 |
legend style | legend style={at={(0.5,-0.2)}} | 自定义图例 |
cycle list name | cycle list name=color list | 循环使用颜色 |
scaled ticks | scaled ticks=false | 禁用刻度缩放 |
restrict y to domain | restrict y to domain=-10:10 | 裁剪极端值 |
绘图类型与示例
折线图(根据表达式绘制)
\begin{axis}[domain=0:2*pi, samples=100, grid=major,
legend pos=south west]
\addplot[blue, thick] {sin(deg(x))};
\addplot[red, thick, dashed] {cos(deg(x))};
\legend{$\sin(x)$, $\cos(x)$}
\end{axis}
折线图(根据数据绘制)
\begin{axis}[xlabel=Year, ylabel=Value]
\addplot coordinates {
(2018, 10) (2019, 15) (2020, 12) (2021, 20) (2022, 25)
};
\end{axis}
散点图
\begin{axis}[only marks, xlabel=$x$, ylabel=$y$]
\addplot[mark=*, blue] coordinates {
(1,2) (2,3.5) (3,2.8) (4,5.1) (5,4.2)
};
% Or with mark options:
\addplot+[mark=o, mark size=3pt, red] coordinates { ... };
\end{axis}
柱状图
\begin{axis}[
ybar, % vertical bars (xbar for horizontal)
symbolic x coords={A, B, C, D},
xtick=data,
ylabel={Count},
nodes near coords, % value labels on bars
bar width=15pt,
]
\addplot coordinates {(A,20) (B,35) (C,30) (D,15)};
\addplot coordinates {(A,25) (B,20) (C,40) (D,10)};
\legend{2022, 2023}
\end{axis}
堆叠柱状图
\begin{axis}[ybar stacked, symbolic x coords={Q1,Q2,Q3,Q4}, xtick=data]
\addplot coordinates {(Q1,10) (Q2,15) (Q3,12) (Q4,18)};
\addplot coordinates {(Q1,8) (Q2,10) (Q3,15) (Q4,12)};
\legend{Product A, Product B}
\end{axis}
直方图
\usepgfplotslibrary{statistics}
\begin{axis}[ybar interval, ylabel=Frequency, xlabel=Value]
\addplot+[hist={bins=10, data min=0, data max=100}]
table[y index=0] {data.csv};
\end{axis}
箱线图
\usepgfplotslibrary{statistics}
\begin{axis}[boxplot/draw direction=y]
\addplot[boxplot prepared={
lower whisker=2, lower quartile=4,
median=6, upper quartile=8, upper whisker=10
}] coordinates {};
\end{axis}
面积图/区间填充
\usepgfplotslibrary{fillbetween}
\begin{axis}
\addplot[name path=upper, blue, thick, domain=0:4] {x^2};
\addplot[name path=lower, red, thick, domain=0:4] {x};
\addplot[fill=blue!10] fill between[of=upper and lower, soft clip={domain=1:3}];
\end{axis}
误差线
\begin{axis}
\addplot+[error bars/.cd, y dir=both, y explicit]
coordinates {
(1, 2) +- (0, 0.5)
(2, 4) +- (0, 0.8)
(3, 3) +- (0, 0.3)
};
\end{axis}
3D 曲面
\begin{axis}[view={45}{30}, xlabel=$x$, ylabel=$y$, zlabel=$z$,
colormap/viridis]
\addplot3[surf, domain=-2:2, domain y=-2:2, samples=25]
{exp(-x^2 - y^2)};
\end{axis}
3D 网格
\begin{axis}[view={60}{30}]
\addplot3[mesh, domain=-2:2, domain y=-2:2, samples=20]
{sin(deg(x)) * cos(deg(y))};
\end{axis}
等高线图
\begin{axis}[view={0}{90}] % top-down view
\addplot3[contour filled, domain=-2:2, domain y=-2:2, samples=30]
{exp(-x^2 - y^2)};
\end{axis}
参数图
\begin{axis}[axis equal]
\addplot[domain=0:360, samples=100, thick, blue]
({cos(x)}, {sin(x)}); % circle
\end{axis}
极坐标图
\usepgfplotslibrary{polar}
\begin{polaraxis}
\addplot[domain=0:360, samples=100, thick]
{1 + cos(x)}; % cardioid
\end{polaraxis}
从文件读取数据
% CSV file: data.csv
% x, y
% 1, 2.3
% 2, 4.1
% ...
\begin{axis}
\addplot table[col sep=comma, x=x, y=y] {data.csv};
% TSV (default separator is space/tab)
\addplot table[x index=0, y index=1] {data.tsv};
% With expression on column
\addplot table[x=time, y expr=\thisrow{value}*100] {data.csv};
\end{axis}
色图
% Built-in colormaps
colormap/hot, colormap/cool, colormap/viridis,
colormap/bluered, colormap/greenyellow, colormap/jet
% Custom
\pgfplotsset{
colormap={mymap}{rgb255(0cm)=(0,0,180); rgb255(1cm)=(0,180,0); rgb255(2cm)=(180,0,0)}
}
% Colorbar
\begin{axis}[colorbar, colormap/viridis]
多坐标轴
\begin{tikzpicture}
\begin{axis}[
axis y line*=left, xlabel=Time, ylabel=Temperature,
ymin=0, ymax=100,
]
\addplot[blue, thick] coordinates {(1,20)(2,40)(3,60)(4,80)};
\label{plot:temp}
\end{axis}
\begin{axis}[
axis y line*=right, axis x line=none,
ylabel=Pressure, ymin=0, ymax=10,
]
\addplot[red, thick, dashed] coordinates {(1,2)(2,5)(3,3)(4,8)};
\label{plot:press}
\end{axis}
\end{tikzpicture}
分组绘图
\usepgfplotslibrary{groupplots}
\begin{tikzpicture}
\begin{groupplot}[
group style={group size=2 by 2, horizontal sep=1.5cm, vertical sep=1.5cm},
width=6cm, height=5cm,
]
\nextgroupplot[title=Plot 1]
\addplot {x};
\nextgroupplot[title=Plot 2]
\addplot {x^2};
\nextgroupplot[title=Plot 3]
\addplot {sqrt(x)};
\nextgroupplot[title=Plot 4]
\addplot {ln(x)};
\end{groupplot}
\end{tikzpicture}
注释
\begin{axis}
\addplot[blue, thick, domain=0:5] {x^2};
% Pin annotation
\node[pin=60:{Maximum}] at (axis cs:4, 16) {};
% Arrow annotation
\draw[->, thick] (axis cs:2, 10) -- (axis cs:3, 9)
node[above, pos=0] {Note};
% Vertical line
\draw[dashed, gray] (axis cs:2.5, 0) -- (axis cs:2.5, 25);
% Horizontal band
\draw[fill=red!10, draw=none] (axis cs:0,5) rectangle (axis cs:5,10);
% Text node
\node at (axis cs:1, 20) {$f(x) = x^2$};
\end{axis}
标记选项
| 标记 | 描述 |
|---|---|
* | 实心圆 |
o | 空心圆 |
square* | 实心方形 |
square | 空心方形 |
triangle* | 实心三角形 |
diamond* | 实心菱形 |
x | 叉号 |
+ | 加号 |
star | 星形 |
none | 无标记 |
\addplot+[mark=triangle*, mark size=3pt, mark options={fill=red}] ...;
常见问题
| 问题 | 原因 | 解决方法 |
|---|---|---|
| “Dimension too large” | 数值或定义域过大 | 使用 restrict y to domain,检查定义域 |
缺少 compat 警告 | 未设置 \pgfplotsset{compat=..} | 添加 \pgfplotsset{compat=1.18} |
| 三角函数结果不正确 | pgfplots 使用角度制 | 弧度输入时使用 sin(deg(x)) |
| 柱条重叠 | 多个柱状图未分组 | 使用 ybar 搭配 bar shift 或图例 |
| 图例位置不正确 | 使用了默认位置 | 设置 legend pos=north west 等 |
| 3D 绘图过慢 | 采样数过多 | 减少 3D 绘图的 samples |
| 坐标轴标签被裁切 | 边界框过紧 | 使用 trim axis left/right 或增大边距 |
| 区间填充失败 | 路径未命名 | 为每个绘图添加 name path=A |
| CSV 列错误 | 分隔符不正确 | 为 CSV 文件设置 col sep=comma |
\addlegendentry 顺序 | 必须紧跟对应的 \addplot | 将图例条目紧接在对应绘图之后 |
评论
支持 Markdown