pgfplots

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

pgfplots — Data Visualization & Plotting

pgfplots — 数据可视化与绘图

CTAN: https://ctan.org/pkg/pgfplots
Manual:
texdoc pgfplots
CTAN: https://ctan.org/pkg/pgfplots
手册:
texdoc pgfplots

Setup

安装配置

latex
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}  % ALWAYS set this — enables latest features

% Optional libraries
\usepgfplotslibrary{fillbetween, groupplots, statistics, colorbrewer, polar}
latex
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}  % 务必设置此项——启用最新功能

% 可选库
\usepgfplotslibrary{fillbetween, groupplots, statistics, colorbrewer, polar}

Basic Plot

基础图表示例

latex
\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}
latex
\begin{tikzpicture}
\begin{axis}[
  xlabel={$x$},
  ylabel={$f(x)$},
  title={我的图表},
  grid=major,
]
  \addplot[blue, thick, domain=-3:3, samples=100] {x^2};
  \addlegend{$x^2$}
\end{axis}
\end{tikzpicture}

Axis Environments

坐标轴环境

EnvironmentDescription
axis
Standard linear axes
semilogxaxis
Log scale on x-axis
semilogyaxis
Log scale on y-axis
loglogaxis
Log scale on both axes
polaraxis
Polar coordinates (requires
polar
library)
环境描述
axis
标准线性坐标轴
semilogxaxis
X轴采用对数刻度
semilogyaxis
Y轴采用对数刻度
loglogaxis
双轴均采用对数刻度
polaraxis
极坐标(需要加载
polar
库)

Axis Options Reference

坐标轴选项参考

OptionExampleDescription
xlabel
xlabel={Time (s)}
X-axis label
ylabel
ylabel={Voltage}
Y-axis label
title
title={Results}
Plot title
xmin/xmax
xmin=0, xmax=10
Axis limits
ymin/ymax
ymin=-1, ymax=1
Axis limits
domain
domain=0:2*pi
Default plot domain
samples
samples=200
Default sample count
grid
grid=major
major
,
minor
,
both
,
none
legend pos
legend pos=north west
Legend placement
width/height
width=10cm
Axis dimensions
axis lines
axis lines=middle
box
,
left
,
middle
,
none
enlargelimits
enlargelimits=0.1
Pad axis range
xtick
xtick={0,1,...,5}
Custom tick positions
xticklabels
xticklabels={A,B,C}
Custom tick labels
x tick label style
x tick label style={rotate=45}
Tick label formatting
legend style
legend style={at={(0.5,-0.2)}}
Legend customization
cycle list name
cycle list name=color list
Color cycling
scaled ticks
scaled ticks=false
Disable tick scaling
restrict y to domain
restrict y to domain=-10:10
Clip extreme values
选项示例描述
xlabel
xlabel={时间 (秒)}
X轴标签
ylabel
ylabel={电压}
Y轴标签
title
title={结果}
图表标题
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
裁剪极端值

Plot Types & Examples

图表类型与示例

Line Plot (from expression)

表达式折线图

latex
\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}
latex
\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}

Line Plot (from data)

数据折线图

latex
\begin{axis}[xlabel=Year, ylabel=Value]
  \addplot coordinates {
    (2018, 10) (2019, 15) (2020, 12) (2021, 20) (2022, 25)
  };
\end{axis}
latex
\begin{axis}[xlabel=年份, ylabel=数值]
  \addplot coordinates {
    (2018, 10) (2019, 15) (2020, 12) (2021, 20) (2022, 25)
  };
\end{axis}

Scatter Plot

散点图

latex
\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}
latex
\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)
  };
  % 或自定义标记选项:
  \addplot+[mark=o, mark size=3pt, red] coordinates { ... };
\end{axis}

Bar Chart

柱状图

latex
\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}
latex
\begin{axis}[
  ybar,                    % 垂直柱状图(xbar为水平柱状图)
  symbolic x coords={A, B, C, D},
  xtick=data,
  ylabel={数量},
  nodes near coords,       % 柱状图上显示数值标签
  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}

Stacked Bar

堆叠柱状图

latex
\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}
latex
\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{产品A, 产品B}
\end{axis}

Histogram

直方图

latex
\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}
latex
\usepgfplotslibrary{statistics}

\begin{axis}[ybar interval, ylabel=频数, xlabel=数值]
  \addplot+[hist={bins=10, data min=0, data max=100}]
    table[y index=0] {data.csv};
\end{axis}

Box Plot

箱线图

latex
\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}
latex
\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}

Area / Fill Between

区域填充/区间填充

latex
\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}
latex
\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}

Error Bars

误差棒图

latex
\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}
latex
\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 Surface

3D曲面图

latex
\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}
latex
\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 Mesh

3D网格图

latex
\begin{axis}[view={60}{30}]
  \addplot3[mesh, domain=-2:2, domain y=-2:2, samples=20]
    {sin(deg(x)) * cos(deg(y))};
\end{axis}
latex
\begin{axis}[view={60}{30}]
  \addplot3[mesh, domain=-2:2, domain y=-2:2, samples=20]
    {sin(deg(x)) * cos(deg(y))};
\end{axis}

Contour

等高线图

latex
\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}
latex
\begin{axis}[view={0}{90}]  % 俯视视角
  \addplot3[contour filled, domain=-2:2, domain y=-2:2, samples=30]
    {exp(-x^2 - y^2)};
\end{axis}

Parametric Plot

参数方程图

latex
\begin{axis}[axis equal]
  \addplot[domain=0:360, samples=100, thick, blue]
    ({cos(x)}, {sin(x)});  % circle
\end{axis}
latex
\begin{axis}[axis equal]
  \addplot[domain=0:360, samples=100, thick, blue]
    ({cos(x)}, {sin(x)});  % 圆形
\end{axis}

Polar Plot

极坐标图

latex
\usepgfplotslibrary{polar}

\begin{polaraxis}
  \addplot[domain=0:360, samples=100, thick]
    {1 + cos(x)};  % cardioid
\end{polaraxis}
latex
\usepgfplotslibrary{polar}

\begin{polaraxis}
  \addplot[domain=0:360, samples=100, thick]
    {1 + cos(x)};  % 心形线
\end{polaraxis}

Data from Files

从文件读取数据

latex
% 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}
latex
% CSV文件:data.csv
% x, y
% 1, 2.3
% 2, 4.1
% ...

\begin{axis}
  \addplot table[col sep=comma, x=x, y=y] {data.csv};
  
  % TSV文件(默认分隔符为空格/制表符)
  \addplot table[x index=0, y index=1] {data.tsv};
  
  % 对列数据进行表达式计算
  \addplot table[x=time, y expr=\thisrow{value}*100] {data.csv};
\end{axis}

Color Maps

颜色映射

latex
% 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]
latex
% 内置颜色映射
colormap/hot, colormap/cool, colormap/viridis,
colormap/bluered, colormap/greenyellow, colormap/jet

% 自定义颜色映射
\pgfplotsset{
  colormap={mymap}{rgb255(0cm)=(0,0,180); rgb255(1cm)=(0,180,0); rgb255(2cm)=(180,0,0)}
}

% 颜色条
\begin{axis}[colorbar, colormap/viridis]

Multiple Axes

多坐标轴

latex
\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}
latex
\begin{tikzpicture}
\begin{axis}[
  axis y line*=left, xlabel=时间, ylabel=温度,
  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=压力, ymin=0, ymax=10,
]
  \addplot[red, thick, dashed] coordinates {(1,2)(2,5)(3,3)(4,8)};
  \label{plot:press}
\end{axis}
\end{tikzpicture}

Group Plots

分组图表

latex
\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}
latex
\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=图表1]
    \addplot {x};
  \nextgroupplot[title=图表2]
    \addplot {x^2};
  \nextgroupplot[title=图表3]
    \addplot {sqrt(x)};
  \nextgroupplot[title=图表4]
    \addplot {ln(x)};
\end{groupplot}
\end{tikzpicture}

Annotations

标注与注释

latex
\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}
latex
\begin{axis}
  \addplot[blue, thick, domain=0:5] {x^2};
  
  % 引脚式标注
  \node[pin=60:{最大值}] at (axis cs:4, 16) {};
  
  % 箭头标注
  \draw[->, thick] (axis cs:2, 10) -- (axis cs:3, 9)
    node[above, pos=0] {注释};
  
  % 垂直线
  \draw[dashed, gray] (axis cs:2.5, 0) -- (axis cs:2.5, 25);
  
  % 水平填充区域
  \draw[fill=red!10, draw=none] (axis cs:0,5) rectangle (axis cs:5,10);
  
  % 文本节点
  \node at (axis cs:1, 20) {$f(x) = x^2$};
\end{axis}

Mark Options

标记点选项

MarkDescription
*
Filled circle
o
Open circle
square*
Filled square
square
Open square
triangle*
Filled triangle
diamond*
Filled diamond
x
Cross
+
Plus
star
Star
none
No marks
latex
\addplot+[mark=triangle*, mark size=3pt, mark options={fill=red}] ...;
标记描述
*
实心圆点
o
空心圆点
square*
实心正方形
square
空心正方形
triangle*
实心三角形
diamond*
实心菱形
x
叉形标记
+
十字标记
star
星形标记
none
无标记
latex
\addplot+[mark=triangle*, mark size=3pt, mark options={fill=red}] ...;

Common Pitfalls

常见问题与解决方法

ProblemCauseFix
"Dimension too large"Large values or domainUse
restrict y to domain
, check domain
Missing
compat
warning
No
\pgfplotsset{compat=..}
Add
\pgfplotsset{compat=1.18}
Trig functions wrongpgfplots uses degreesUse
sin(deg(x))
for radians input
Bars overlappingMultiple bar plots without groupingUse
ybar
with
bar shift
or legend
Legend in wrong spotDefault positionSet
legend pos=north west
etc.
3D plot too slowToo many samplesReduce
samples
for 3D
Axis labels cut offTight bounding boxUse
trim axis left/right
or increase margins
Fill between failsPaths not namedAdd
name path=A
to each plot
CSV column errorWrong separatorSet
col sep=comma
for CSV files
\addlegendentry
order
Must follow its
\addplot
Put legend entry right after its plot
问题原因解决方法
"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
之后