1. 概述
本文将学习如何在 LaTeX 文档中绘制图表和图形。
首先,我们将讨论 LaTeX 作为计算机科学可视化工具的使用方式。
接着,我们会通过一个完整示例来绘制一个非线性激活函数对比图,还会学习如何绘制箱线图和柱状图以比较多个分布。
学完本文后,你将掌握在 LaTeX 中绘制基本图表的方法。
2. LaTeX 中的绘图
2.1. LaTeX、图表与计算机科学
LaTeX 是一种功能强大的编程与标记语言,用于创建可自定义的文档。它在机器学习文献中广泛使用,因为它便于撰写描述数据集、模型架构以及算法优化的论文。
✅ LaTeX 也支持图表和图形的创建和完全自定义。这通过使用专用宏包实现,下一节将详细介绍。因为原生 LaTeX 在这方面功能有限,所以通常依赖宏包扩展其能力。
在计算机科学和机器学习中,图表绘制是一项常见任务,尤其是可视化方向。在科研论文中,LaTeX 是核心工具之一,因为它输出的是完整的文档,而不仅仅是图表。因此,所有主要会议都提供 LaTeX 模板,并要求将图表嵌入其中。
⚠️ 掌握如何在 LaTeX 中绘制图表是非常重要的技能,本文将带你掌握它。
2.2. 用于绘图的 LaTeX 宏包
LaTeX 中的绘图主要依赖宏包。最常用的两个是:
- TikZ:全称 PGF/TikZ,是用于绘制几何图形的基础宏包
- PGFPlots:基于 TikZ,进一步扩展了其功能,特别适合绘制函数图、箱线图、柱状图等统计图表
这两个宏包足以应对大多数 2D 和 3D 图表的绘制需求。本文重点介绍 2D 图表的绘制方法,但如果你需要,也可以用它们绘制 图结构 或 有限状态机。
3. 在 TikZ 中绘制函数图
3.1. 绘制笛卡尔坐标系
我们以绘制 逻辑斯蒂函数(如 逻辑回归 中使用的函数)为例,同时绘制其他 S 型函数,展示它们形状上的差异。
绘制函数图的第一步是绘制笛卡尔坐标轴。这可以在 tikzpicture
环境中使用两次 \draw[->]
命令完成:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw[->] (-3.1,0) -- (3.1,0) node[right] {$x$};
\draw[->] (0,-2.1) -- (0,2.1) node[above] {$y$};
\end{tikzpicture}
\end{document}
输出效果如下:
3.2. 缩放与网格线
当前图表显示了坐标轴和标签。由于 S 型函数的值域较窄,我们让横轴更长一些。图表在页面中显得较小,可以通过在 tikzpicture
环境中添加 scale
参数来放大:
\begin{tikzpicture}[scale=2]
这样图表尺寸变为原来的两倍:
图表现在尺寸合适,但仍是空的。我们可以添加虚线网格帮助读取函数值:
\draw[dotted] (-3.1,-2.1) grid (3.1,2.1);
现在图表中有了虚线网格:
3.3. 绘制函数曲线
坐标系已经完成,现在可以绘制函数了。使用 \draw plot function{}
命令即可,语法如下:
\draw[参数] plot[参数] function{函数表达式};
建议始终为 plot
添加 id
参数以便后续引用。我们先绘制蓝色的逻辑斯蒂函数:
\draw[color=blue] plot[id=logistic] function{1/(1+exp(-x))};
输出如下:
函数在左侧延伸过远,可以设置 tikzpicture
的 domain
参数限制绘图范围:
\begin{tikzpicture}[scale=2, domain=-3:3]
限制后输出如下:
我们还可以为曲线添加标签:
\draw[color=blue] plot[id=logistic] function{1/(1+exp(-x))} node[right] {$f_1(x) = \frac{1}{1+e^{-x}}$};
效果如下:
3.4. 绘制更多 S 型函数
我们还可以绘制其他 S 型函数进行比较:
- 双曲正切函数:
$f_2(x) = \text{tanh}(x)$
- 代数函数:
$f_3(x) = \frac{x}{\sqrt{1+x^2}}$
- 反正切函数:
$f_4(x) = \text{arctan}(x)$
分别使用 \draw plot
命令绘制:
\draw[color=red] plot[id=hypertan] function{tanh(x)} node[above right] {$f_2(x) = tanh(x)$};
\draw[color=orange] plot[id=algebraic] function{x/sqrt(1+x*x)} node[below right] {$f_3(x) = \frac{x}{\sqrt{1+x^2}}$};
\draw[color=brown] plot[id=arctangent] function{atan(x)} node[above right] {$f_4(x) = arctan(x)$};
输出如下:
3.5. 最终润色
标签有些重叠,可以为 right
、above right
等参数添加 =0.15cm
调整间距:
node[right=0.15cm]
为了让曲线更清晰,可以加上 very thick
属性:
\draw[very thick, color=blue]
最后,添加标题:
\node[align=center, font=\bfseries, yshift=2em, xshift=-4.5em] (title) at (current bounding box.north) {Sigmoidal functions};
输出如下:
3.6. 完整代码
以下是完整的 TikZ 函数图绘制代码:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[scale=2, domain=-3:3]
\draw[->] (-3.1,0) -- (3.1,0) node[right] {$x$};
\draw[->] (0,-2.1) -- (0,2.1) node[above] {$y$};
\draw[dotted] (-3.1,-2.1) grid (3.1,2.1);
\draw[very thick, color=blue] plot[id=logistic] function{1/(1+exp(-x))} node[right=0.15cm] {$f_1(x) = \frac{1}{1+e^{-x}}$};
\draw[very thick, color=red] plot[id=hypertan] function{tanh(x)} node[above right=0.15cm] {$f_2(x) = tanh(x)$};
\draw[very thick, color=orange] plot[id=algebraic] function{x/sqrt(1+x*x)} node[below right=0.15cm] {$f_3(x) = \frac{x}{\sqrt{1+x^2}}$};
\draw[very thick, color=brown] plot[id=arctangent] function{atan(x)} node[above right=0.15cm] {$f_4(x) = arctan(x)$};
\node[align=center, font=\bfseries, yshift=2em, xshift=-4.5em] (title) at (current bounding box.north) {Sigmoidal functions};
\end{tikzpicture}
\end{document}
4. 使用 PGFPlots 绘制箱线图
4.1. PGFPlots 与统计分析
除了 TikZ,我们还可以使用 PGFPlots 进行图表绘制。PGFPlots 是基于 TikZ 的扩展宏包,简化了常见图表的创建过程。
我们来绘制一个箱线图,用于比较四个班级学生的考试成绩分布。我们根据学生在课堂上的专注程度给班级命名,并通过统计分析验证我们的预期。
箱线图非常适合初步数据分析,常用于查看训练机器学习模型前的数据集结构。
使用 PGFPlots 的箱线图需要引入 statistics
库:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\usepgfplotslibrary{statistics}
\begin{document}
\begin{tikzpicture}
\begin{axis}[xlabel={$x$}, ylabel={$y$}, title=Box Plot]
% 箱线图将放在这里
\end{axis}
\end{tikzpicture}
\end{document}
4.2. 添加箱线图
PGFPlots 的箱线图接受以下参数:
- 中位数
- 下四分位数和上四分位数(对应 25% 和 75% 分位数)
- 下须和上须(通常表示均值的一个标准差)
如果已有这些数据,可以直接使用 \addplot+ boxplot prepared
添加:
\addplot+ [boxplot prepared={lower whisker=25, lower quartile=37, median=65, upper quartile=72, upper whisker=81}]
table[row sep=\\,y index=0] {1\\ 92\\ 95\\};
输出如下:
4.3. 多个箱线图对比
可以重复使用 \addplot+
添加多个箱线图:
\addplot+ [boxplot prepared={...}] ...;
\addplot+ [boxplot prepared={...}] ...;
输出如下:
4.4. 添加标签
默认的 y 轴标签不具信息量,可以设置 ytick
和 yticklabels
:
\begin{axis}[xlabel={Score}, title={Exam results}, ytick={1,2,3,4},
yticklabels={Attentive students, Inattentive students, Normal students, Highly participating students}]
效果如下:
4.5. 完整代码
以下是完整的箱线图代码:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\usepgfplotslibrary{statistics}
\begin{document}
\begin{tikzpicture}
\begin{axis}[xlabel={Score}, title={Exam results}, ytick={1,2,3,4},
yticklabels={Attentive students, Inattentive students, Normal students, Highly participating students}]
\addplot+ [boxplot prepared={lower whisker=25, lower quartile=37, median=65,
upper quartile=72, upper whisker=81}] table[row sep=\\,y index=0] {1\\ 92\\ 95\\};
\addplot+ [boxplot prepared={lower whisker=12, lower quartile=17, median=25,
upper quartile=52, upper whisker=61}] table[row sep=\\,y index=0] {72\\};
\addplot+ [boxplot prepared={lower whisker=12, lower quartile=25, median=50,
upper quartile=75, upper whisker=87}] table[row sep=\\,y index=0] {};
\addplot+ [boxplot prepared={lower whisker=62, lower quartile=64, median=70,
upper quartile=72, upper whisker=81}] table[row sep=\\,y index=0] {5\\9\\13\\};
\end{axis}
\end{tikzpicture}
\end{document}
5. 使用 PGFPlots 绘制柱状图
5.1. 定义环境
柱状图适合比较多个相同类型的数据分布。例如,我们可以用柱状图比较三家公司(包括我们自己的公司)在上一财年的支出情况。
定义 axis
环境并设置 ybar
和标题:
\begin{axis}[ybar, title={Company expenses in 2019}]
如果使用 xbar
,则会绘制横向柱状图,但财务数据通常使用纵向柱状图。
设置 symbolic x coords
来定义横轴为分类数据:
symbolic x coords={Salaries, Capital, Loans, Taxes}
效果如下:
5.2. 添加柱状图
使用 \addplot+ coordinates
添加数据:
\addplot+ coordinates {(Salaries, 150) (Capital, 158) (Loans, 142) (Taxes, 164)};
效果如下:
标签有重叠,可以设置 enlarge x limits=0.2
解决:
enlarge x limits=0.2
效果如下:
5.3. 最终润色
添加图例和柱子顶部的数值:
legend pos=north west,
nodes near coords,
axis y line=none,
axis x line=bottom
最终效果如下:
5.4. 完整代码
以下是完整的柱状图代码:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}
\begin{axis}[ybar, title={Company expenses in 2019},
symbolic x coords={Salaries, Capital, Loans, Taxes},
legend pos=north west, axis y line=none, axis x line=bottom,
nodes near coords, enlarge x limits=0.2]
\addplot+ coordinates {(Salaries, 150) (Capital, 158) (Loans, 142) (Taxes, 164)};
\addplot+ coordinates {(Salaries, 143) (Capital, 146) (Loans, 169) (Taxes, 182)};
\addplot+ coordinates {(Salaries, 162) (Capital, 156) (Loans, 149) (Taxes, 165)};
\legend{Our company, Competitor 1, Competitor 2};
\end{axis}
\end{tikzpicture}
\end{document}
6. 总结
本文介绍了如何在 LaTeX 中绘制基本图表:
- 使用 TikZ 绘制函数图
- 使用 PGFPlots 绘制箱线图和柱状图
掌握了这些方法后,你就可以在 LaTeX 文档中自由地添加图表,增强论文或报告的表现力。