TiKZ绘制折线图
本文介绍了TiKZ宏包在LaTeX中的强大矢量绘图功能,包括基础绘图、高级图形绘制和专业领域支持。
提供了一个折线图绘制模板,包括LaTeX代码和数据文件示例。还介绍了Make自动化编译配置,包括编译LaTeX文件和将PDF转换为SVG格式。
最后展示了绘制的折线图结果。
TiKZ
TikZ(TikZ ist kein Zeichenprogramm,意为“TikZ不是绘图程序”)是LaTeX中最强大的矢量绘图宏包之一,基于PGF(Portable Graphics Format)开发,通过代码精确控制图形细节,适用于学术论文、技术文档中的高质量插图。
基础绘图能力
- 几何图形:点、线、圆、矩形等基本元素。
- 路径操作:支持直线(–)、曲线(.. controls ..)、函数图像(
\draw plot
)。 - 节点与标签:通过
\node
添加文本标签,支持位置调整与样式定制。
高级图形绘制
- 神经网络/流程图:用节点(
node
)和连接线(edge
)构建复杂结构。 - 函数图像:结合 pgfplots 库绘制2D/3D函数、统计图表。
- 科学图示:如线性代数变换、围道积分、电路图(需
circuitikz
库)。
专业领域支持
- 物理学:Feynman图(tikz-feynman 库)、Penrose图(时空图)。
- 数学证明:无字证明、三角函数公式的可视化。
模板
绘制折线图可以参考下面的模板:
\documentclass{standalone}
\usepackage[fontset=none]{ctex}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\setCJKmainfont{HYShuFang}
\setmainfont{FiraCode Nerd Font}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
title={页面加载时间},
font=\scriptsize, % 全局基准字体
xlabel=次数,
ylabel=时间/s,
xlabel style={font=\tiny, yshift=0.5em},
ylabel style={font=\tiny},
xticklabel style={font=\tiny},
yticklabel style={font=\tiny},
ymax=2,
grid=major, % 网格用major
legend pos=north east, % 图例位置改为底部外侧
legend style={
font=\tiny,
legend columns=1, % 分3列显示(按需调整)
legend cell align=left, % 靠左对齐
% draw=none, % 隐藏图例外框(可选)
% xshift=-10pt, % 向左移动 10pt
% yshift=-20pt % 向下移动 5pt
}
]
%
\addplot[blue, mark=*, smooth] table[x=次数, y=时间, col sep=space] {./demo1.dat};
\addlegendentry{设备1}
\addplot[red, mark=square, smooth] table[x=次数, y=时间, col sep=space] {./demo2.dat};
\addlegendentry{设备2}
\end{axis}
\end{tikzpicture}
\end{document}
使用的dat数据文件demo1.dat
示例如下:
次数 时间
1 2.20
2 2.24
3 2.24
4 1.91
5 2.24
6 2.24
7 2.14
8 2.24
9 2.24
10 2.11
使用make
编译的前提是需要在Linux系统上安装texstudio
和pdf2svg
。
Make自动化编译配置如下:
SRC=$(wildcard *.tex)
OBJ=$(patsubst %.tex,%.aux,${SRC})
OBJ+=$(patsubst %.tex, %.log, ${SRC})
OBJ+=$(patsubst %.tex, %.pdf, ${SRC})
PDF=$(patsubst %.tex, %.pdf, ${SRC})
SVG=$(patsubst %, %.svg, ${PDF})
CC=xelatex
.PHONY: all
all: build install
.PHONY: build
build: ${SRC}
# echo ${SRC}
# 逐个编译tex文件
for item in ${SRC}; do ${CC} $${item}; done
# 下面通过pdf2svg工具将生成的pdf转为svg图片格式
for item_pdf in ${PDF}; do pdf2svg $${item_pdf} $${item_pdf}.svg;done
.PHONY: clean
clean:
# echo ${OBJ}
rm -rf ${OBJ}
rm -rf ${SVG}
rm -rf ${PDF}
rm -rf texput.log
.PHONY: install
install:
# 拷贝到共享文件夹中,可以在windows上打开
cp ${SVG} ~/windows_share/temp/
绘制图示结果:
- 原文作者:生如夏花
- 原文链接:https://DBL2017.github.io/post/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/latex/tikz%E7%BB%98%E5%88%B6%E6%8A%98%E7%BA%BF%E5%9B%BE/
- 版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。