图是一份清单,不是一块画布
TikZ 改变的只有一件事,其余一切都跟着来:一张图是被描述出来的,而不是被拖出来的。它的节点、坐标、箭头和颜色,是与正文写在同一个文件里的若干行,于是这张图参与版本控制、一次 diff 就能显出改了什么、重新构建也不可能悄悄产出一张与评审时不同的图,而且没有会弄丢的选择工具,也没有要找的 final_final_v3.png。节点里的文字由排版上面那句正文的同一个 TeX 排版,这就是为什么一张 TikZ 图从来不像贴进来的。
语法底下有两层。PGF 是底层的键与路径机器;TikZ 是你真正敲的那种可读的前端,而 \usepackage{tikz} 会加载 PGF 并问它当前在用哪个图形驱动——pdftex.def、luatex.def、dvips.def、dvisvgm.def。这层间接正是一份源码变成 PDF、PostScript 文件或者 SVG 而一字不改的原因,它同样也是为什么颜色与透明度在 lualatex 和 xelatex 下比在最老的引擎上走得更远。额外的行为不是内置的,是加载进来的:\usetikzlibrary{positioning,calc,arrows.meta} 每键组拉进一个文件,而忘了这一行,是一大半 TikZ 报错的源头。
你付出的是那个循环:你得编译才能看见。拖动的时候什么都不动,因为根本没有可拖的东西,而一个写错的坐标会一直错到下一次运行。第一张图要一小时;第二十张只要几分钟,因为这套词汇是有限而固定的——一个节点、一条路径、一个选项列表、一个样式、一个库。也值得早点知道这件工具的边界:TikZ 画的是插图,而 pgfplots 画的是图表。一张两轴上带数字的图是另一个宏包的活,因为它从数据里、而不是从你的耐心里,算出尺度、刻度的位置和图例。

节点、坐标,以及节点内部的数学
一个节点有四个部分,其中只有一个非写不可:\node[⟨options⟩] (⟨name⟩) at (⟨coordinate⟩) {⟨text⟩};——名字是带括号的那一小段,不是文字,而 \draw (A) -- (B); 只有在你写了那对括号时才管用。\coordinate (O) at (0,0); 是一个不带任何墨迹的名字,这正是你标出一个稍后要连的中点、而页面上什么都不出现的方式。第一天还该学的另一种形式是路径末尾的节点:\draw (0,0) -- (2,1) node[midway, above] {f}; 把标签放到它所跟随的那条线段上,而把文字放到箭头旁边用的正是同一个构造。
每个节点都是一个盒子,而盒子有命名点:(A.center)、(A.north)、(A.south west)、它所画形状的那些边界锚点,而圆形还有按角度的——(A.30) 是从圆心出发转过三十度的那个点。anchor= 选项随后决定把这些点中的哪一个放到你给的那个坐标上,这就是为什么同一行 \node 会落在比你预期两厘米远的地方。坐标默认是以厘米为单位的一对数,所以 (2,3) 意思是右移 2cm、上移 3cm,而一个单位意味着什么本身可以通过 x= 和 y= 来调。
节点文字就是水平模式里普通的 LaTeX,而这正是 TikZ 在数学插图上打赢图片编辑器的全部理由:节点里的积分由引擎排版、用文档的字体、按文档的尺寸。三个后果很早就咬人。数学需要自己的美元符号,所以 \node {x_1} 会止于 ! Missing $ inserted.,而同样内容夹在两个美元之间就没事——并且节点里的美元给你的是文本样式的数学,也就是下面那块里的小号分式和搁在侧面的上下限;修法是 \displaystyle、\dfrac,或者 mathnodes 库里的 math 键。节点内部要换行,得先有 align=center 或 text width=。而在 matrix 里,& 是单元格分隔符,所以一个要自带对齐的单元格需要 ampersand replacement=\&。
P(A \mid B) = \frac{P(B \mid A)\, P(A)}{P(B)}
% Preamble: \usepackage{tikz}
\begin{tikzpicture}[node distance=22mm]
\node[draw, circle] (A) {A};
\node[draw, circle] (B) [right of=A] {B};
\node[draw, circle] (C) [right of=B] {C};
\draw[->] (A) -- (B);
\draw[->] (B) -- (C)
node[midway, above] {f};
\end{tikzpicture}
路径:draw、fill 和那个分号究竟在做什么
一张图里所有看得见的东西都是一条路径:一串算子列表——-- 是直线段,-| 和 |- 是拐角,to[bend left] 与 .. controls .. .. 是曲线,circle、rectangle、arc、grid——而节点可以出现在列表里的任何位置。路径只在结束它的那个分号处被执行。在那之前,页面上什么都不存在,这就是为什么一个标签可以写在一行的中间,也为什么一个漏掉的 ; 从来不会在它漏掉的那一行上报错。
前缀说这条完工的路径要怎么样:\draw 描它的边,\fill 涂它的内部,\filldraw 两者都做、而两者重叠处顺序有讲究,\shade 用渐变填充它,而光秃秃的 \path 只算几何什么都不画——这就是在不该出现线条的地方放下一个 \coordinate 或一个标签的常用手法。外观住在选项列表里:line width=0.6pt 以及从 ultra thin 到 ultra thick 的那些具名档位、dashed、densely dotted、dash pattern=on 2pt off 3pt、rounded corners=2pt、line cap=round、opacity=0.4,还有用感叹号混出来的颜色如 red!40!black,后者除 TikZ 本身什么都不需要。
选项可以在一条路径的中间改——\draw[thick] (0,0) -- (1,1) [dashed] -- (2,1);——这就是为什么一条连接线可以在它是事实的地方保持实线、在它是假设的地方变成虚线。-| 和 |- 是那种两段式拐角,用来把一条边绕着一个盒子走而不是穿过去,而 to[out=20,in=160] 是一条角度可读的贝塞尔曲线,不必去想象两个控制点。这一节也是两个错误的案发地:一个忘掉的 ;,以及一个没关上的花括号或方括号,它会让 TeX 在剩下的整张图里去找那个闭合符号。两者都会给出一条行号并不是你写坏的那一行的错误。
% The same picture, straight lines and no library:
\begin{tikzpicture}
\draw[fill=blue!15] (0,0) circle (8mm);
\draw[thick, ->] (8mm,0) -- (26mm,0)
node[right] {v};
\draw[dashed] (0,0) -- (26mm,0);
\end{tikzpicture}
positioning 与 calc:说到做到的距离
两个盒子加一支箭头,是这门语言里被重复最多的构造,而它有两种语法、底下的几何并不相同。right of=A 是 TikZ 0.x 的原初形式——今天仍然接受、仍然活在网络上每个老回答里——它量的是圆心到圆心,所以 node distance 并不是你看见的那个间隙,而一个更宽的标签会安静地把它吃掉。right=of A,来自 positioning 库,量的是从 A 的东侧边界锚点到新节点的西侧边界锚点:那个间隙就是你写下的距离,不管两个盒子里装了什么文字。如果你接手的一份清单长得像这一页上第一块那样,那它正在做的就是这件事。
positioning 的其余部分是同一个想法配上更多方向:below left=of A 走对角线,right=2cm of A 为一个节点覆盖一个距离,还有两值形式 below=8mm and -18mm of A,其中第二个数是垂直方向的偏移、负号把方向翻过来。on grid 有意把基于圆心的摆放带回来:距离再次按圆心之间量,但这些圆心会吸附到一张共享网格上,这正是一格一格那些盒子能对齐的原因。node distance=14mm 为整张图设默认值,而每一次摆放都可以各自覆盖它,这也是让某一对盒子比其他更紧的常用做法。
calc 是不用手做几何的另一半。$(A)!0.5!(B)$ 是中点,$(A)!1.6!(B)$ 把直线继续伸到 B 之外,$(A)!0.5!90:(B)$ 是那个中点绕 A 转九十度,$(A)!(B)!(C)$ 是从 B 向过 A 与 C 的直线作垂线的垂足,而 ([xshift=-3pt]A.north west) 能平移任何坐标,锚点也算。有了 let 你可以把测量值读回来——\path let \p1 = ($(Q)-(P)$), \n1 = {veclen(\x1,\y1)} in 把两个节点之间的距离给出为一个可打印、可使用的长度。这两套键都是库:没有 \usetikzlibrary{positioning,calc},那个 = 形式不只是难看,它根本不存在,而 pgfkeys 的抱怨会点名它找不到的那个键。
M = \frac{A + B}{2}, \qquad P(t) = A + t\,(B - A), \quad t \in \mathbb{R}
\documentclass[a4paper]{article}
\usepackage{tikz}
% The two syntaxes that place one node relative to another, and the point
% arithmetic at the end of this file, both live in these two libraries:
\usetikzlibrary{positioning,calc}
\begin{document}
% ---- 1. the modern form: node distance is measured BETWEEN BORDERS
\begin{tikzpicture}[node distance=14mm]
\node[draw, rounded corners] (in) {sensor};
\node[draw, rounded corners, right=of in] (proc) {filter};
\node[draw, rounded corners, below=of proc] (out) {log};
% two-value form: the named distance first, the perpendicular one second;
% a negative value moves the node the other way along that axis
\node[draw, rounded corners, below=8mm and -18mm of proc] (alarm) {alarm};
\draw[->] (in) -- (proc);
\draw[->] (proc) -- (out);
\draw[->] (proc) -- (alarm);
\end{tikzpicture}
% ---- 2. the deprecated form: it measures CENTRE to CENTRE, so the gap you
% see is node distance minus half of each node width -- and it
% shrinks by itself as soon as somebody adds words
\begin{tikzpicture}[node distance=26mm]
\node[draw] (a) {a};
\node[draw, right of=a] {a far wider node};
\end{tikzpicture}
% ---- 3. on grid: centres snap onto a shared grid, which is what you actually
% want for a row of boxes whose columns must line up
\begin{tikzpicture}[node distance=26mm, on grid]
\node[draw] (b) {one};
\node[draw, below right=of b] {two};
\end{tikzpicture}
% ---- 4. calc: name the points you never drew
\begin{tikzpicture}
\node[draw, circle] (P) at (0,0) {$P$};
\node[draw, circle] (Q) at (4,1.5) {$Q$};
\coordinate (M) at ($(P)!0.5!(Q)$); % midpoint
\coordinate (R) at ($(P)!1.6!(Q)$); % past Q: the segment extended
\coordinate (F) at ($(P)!(Q)!(0,4)$); % foot of the perpendicular
% from Q onto the line P-(0,4)
\coordinate (G) at ($(P)!0.5!90:(Q)$); % midpoint, turned 90 about P
\coordinate (S) at ([xshift=3pt,yshift=-3pt]P.north east); % any anchor, shifted
\draw[thick] (P) -- (Q);
\draw[densely dashed] (Q) -- (F);
\foreach \pt in {M,R,F,G,S} \fill (\pt) circle[radius=1.6pt];
\end{tikzpicture}
% ---- 5. let: read a measurement back out of the picture instead of typing it
\begin{tikzpicture}
\node (P) at (0,0) {$P$};
\node (Q) at (3,1) {$Q$};
\path let \p1 = ($(Q)-(P)$), \n1 = {veclen(\x1,\y1)} in
(P) node[below right, font=\footnotesize] {the length of $PQ$ is \n1};
\end{tikzpicture}
\end{document}
箭头、带标签的边,以及数学更强的地方
一支箭头是一条带尖的路径:[->]、[<-]、[<->],而默认那个尖是故意朴素的。有人在维护的库是 arrows.meta,它的名字是 Stealth、Latex、Triangle、Circle 和 Bar,需要选项时就写进方括号里——[-{Stealth[length=2.4mm]}]、[-{Triangle[angle=60:3pt]}]——而 >=Stealth 设定一张图余下部分里一个普通 -> 是什么意思,写在导言区时对整篇文档有效。更老的 arrows 库——你在几乎每个存档回答里都会遇到它——用小写名字,并在尾部加一个撇号来反转一个尖:[stealth'-]。它早于 arrows.meta,也配置不了尖的尺寸,这就是为什么新文件该写新名字。
边上的一个标签就是路径上的一个节点,所以摆放用的键就是前面几节那些:midway、near start、pos=0.65 决定沿线多远;above、below、left、right 决定哪一侧;还有 sloped,它把文字旋转去跟随一条不水平的线。一个压在线条正上方的标签需要一个背景,否则笔画会从字形后面透出来——fill=white, inner sep=1.5pt 就是那两键的消隐,而 font=\scriptsize 让标签比它注释的节点更小。同一对盒子之间的两支箭头,是一条带 bend left=16 的路径;而 edge[bend left] 允许一条支路离开你正在建的路径、之后再回到它上面。
不过在行文里,TikZ 是输的那一个。一个 tikzpicture 是一个盒子,在你用 baseline=(A.base) 告诉它之前,它并不知道自己落在哪一行的基线上,而且它不会随周围的数学一起拉伸或收缩。所以一支属于某个方程的箭头就留在方程里:amsmath 的 \xrightarrow{f} 把标签放在箭杆上方、保住那一行自己的基线,并随周围公式的尺寸一起缩放。让两者都好看的规则很短:几何用图,记号用数学。
A \hookrightarrow B \twoheadrightarrow C \qquad x \longmapsto \varphi(x)
amsmath 的箭头会加入它所写身的那条基线,而这正是一张行内图片需要被吩咐才肯做的活。\documentclass[a4paper]{article}
\usepackage{tikz}
% arrows.meta is the maintained tip library; positioning is for the =of forms.
\usetikzlibrary{arrows.meta,positioning}
\tikzset{%
>={Stealth[length=2.2mm]}, % what a plain -> now means from here on
flow/.style = {->, thick},
box/.style = {draw, rounded corners, minimum width=14mm},
% a label that sits ON a line needs a background, or the line reads through it
elab/.style = {font=\scriptsize, inner sep=1.5pt, fill=white},
}
\begin{document}
\begin{tikzpicture}[node distance=16mm]
\node[box] (q0) {$q_0$};
\node[box, right=of q0] (q1) {$q_1$};
\node[box, below=of q0] (qd) {$q_d$};
% pos = how far along, above/left = which side, sloped = follow the line
\draw[flow] (q0) -- node[elab, above] {$a{,}b$} (q1);
\draw[flow] (q0) -- node[elab, left] {$\varepsilon$} (qd);
\draw[flow] (q1) -- node[elab, right, pos=0.35] {$\tau$} (qd);
% two arrows between the same pair of nodes: bend one of them
\draw[flow] (q1) to[bend left=16]
node[elab, above, sloped] {$b$} (q0);
% tips written out by name, with their own size, and a path that turns
\draw[-{Triangle[angle=60:3pt]}, shorten >=1pt]
(qd) -- ++(-1.6,0) node[left] {reject};
\draw[{Circle[length=2pt]}-{Stealth[length=2.6mm]}]
(q1) ++(0,0.6) -- ++(1.4,0) node[right, font=\scriptsize] {reset};
% -| and |- are cornered paths: the way to route an edge around a box
\draw[flow] (q1) |- node[elab, near end, below] {$c$} ++(1.8,-1.2);
\end{tikzpicture}
\end{document}
样式、tikzset 与 every node:整篇文档一个长相
在三十个节点上重复 draw, thick, rounded corners=2pt, minimum width=14mm,是一个你在第三十一个上就会违约的承诺。样式把那个列表变成一个名字:\tikzset 内部的 base/.style={…} 在 /tikz/ 命名空间里安装一个键,样式靠在自己的列表里点另一个名字来组合,而 base/.append style={minimum height=8mm} 不改写它就细化一个——期刊类文档调整一套它并没有写过的规范样式,靠的就是这个。.style args={#1,#2} 接收参数,调用成 [tint={red,14}],它包办了你否则只能逐个列举的各种颜色变体。
另一半是你从来不去调用的那些样式:every node/.style,以及它的亲戚 every picture、every path、every edge、every pin。它们能抵达那些没人记得打标签的节点,这就是「一张一致的图」与「一张有三十个节点、四种标签字号的图」之间的差别。font=、inner sep=、outer sep= 和 minimum size= 那一族属于那里,因为它们是审稿人会全局要求的那些设置,也因为一个尺寸键只是一个下限:装的文字多于 minimum width 的节点会长大,所以样式也是你放 align= 或 text width= 去止住这种生长的地方。
存活期决定一个选项该放哪里,而这正是防意外的那一部分。\begin{tikzpicture}[…] 上的选项抵达那一张图里的每一条路径,并在它的 \end{tikzpicture} 处停下;scope 上的选项在它的 \end{scope} 处停下;导言区里的一次 \tikzset 活到下一次 \tikzset 为止,这也是不碰任何一张图就能做出全篇统一长相的原因。两个错误来自顺序:\tikzset 写在 \usepackage{tikz} 之前,就是第一个 token 上的 ! Undefined control sequence.;而一个在当前命名空间里没定义的键,会产出一条点名完整路径的 pgfkeys 消息,/tikz/…——这也是你分辨笔误与缺失库的办法。
\documentclass[a4paper]{article}
\usepackage{tikz}
\usetikzlibrary{arrows.meta,positioning}
% A house style belongs in the preamble. \tikzset installs keys in the
% /tikz/ namespace, so every later picture can use them and one edit
% changes every figure in the document.
\tikzset{%
base/.style = {draw, thick, rounded corners=2pt, minimum width=14mm,
minimum height=7mm, align=center, font=\small},
% styles compose: name another style inside the list and add to it
io/.style = {base, fill=blue!7, draw=blue!55!black},
state/.style = {draw, circle, inner sep=1.5pt, minimum size=8mm},
flow/.style = {->, thick, >=Stealth},
elab/.style = {font=\scriptsize, inner sep=1.5pt, fill=white},
% a style that takes arguments: call it as [tint={red,14}]
tint/.style args={#1,#2}{draw=#1!60!black, fill=#1!#2},
% the nodes nobody remembered to tag:
every node/.style = {font=\small},
}
% Refining a style later does not mean rewriting it:
\tikzset{base/.append style={minimum height=8mm}}
\begin{document}
\begin{tikzpicture}[node distance=15mm]
\node[io] (adc) {ADC\\$2\,\mathrm{kHz}$};
\node[base, right=of adc] (filt) {moving average};
\node[state, below=of filt] (s) {$s_2$};
\node[tint={red,14}, right=of filt] (alarm) {alarm};
\draw[flow] (adc) -- node[elab, above] {$x_k$} (filt);
\draw[flow] (filt) -- node[elab, left] {$y_k$} (s);
\draw[flow] (filt) -- node[elab, above] {$\theta$} (alarm);
\end{tikzpicture}
% Lifetime is what separates the three places an option may go: options on
% \begin{tikzpicture} live to \end{tikzpicture}, options on a scope live to
% \end{scope}, and a \tikzset lives until the next \tikzset.
\begin{tikzpicture}[line width=0.8pt]
\draw (0,0) -- (1,1);
\begin{scope}[line width=0.15pt, densely dashed, red!60!black]
\draw (1,0) -- (2,1);
\node[fill=white, font=\scriptsize] at (1.5,0.5) {inside the scope};
\end{scope}
\draw (2,0) -- (3,1); % 0.8pt and black again
\end{tikzpicture}
\end{document}
scope、变换与画布:scale 到底缩放了什么
\begin{scope}[⟨options⟩] 把一张图的两半都括起来。里面画的一切继承这些选项,里面的坐标可以整组移动,而 \end{scope} 结束这个效果——嵌套是常态,而在一张四十个节点的图里,scope 就是你让一次试验不去给其余部分重新上色的办法。这些键就是那套平常的变换集:shift={⟨coordinate⟩}、xshift=、yshift=、rotate=⟨deg⟩、rotate around={⟨angle⟩:(⟨point⟩)}、scale=、xscale=、yscale=、xslant=,以及具名键表达不了的东西所用的裸 cm= 矩阵。
那个每个人都只会被惊到一次的:scale 变换的是几何,而文字不是几何。一个被缩放的节点保住它的字号,于是图排出来是盒子变大了、字母还是那么小,除非你再加上 transform shape——而那又会把文字、线宽和间距一起缩放,那也未必是你想要的。transform canvas 是第三个层级:它变换坐标系统本身,让绘制的内容可以落到那张图报告为自身边界的区域之外,也正是墨迹会在页面边缘附近失踪的原因。要改单位而不是做畸变,就去设 x=、y= 和 z=:那三个定义了 (1,0) 与 (0,1) 各是什么意思,于是一条斜轴或一个等距立方体就变成两行的改动,而不是重新推导一遍。
两个较小的 scope 工具很早就回本。local bounding box=⟨name⟩ 把一个 scope 画出的所有东西包进一个以它命名的矩形节点里,于是一组箭头和盒子变成一个你可以摆放、填充或连接的东西——面对「我怎么给这四个节点画一个外框」这个问题,这是诚实的答案。而 \foreach \k in {0,…,5} 压根不需要任何库,它就是一个重复被写一次的方式:在 scope 里配上 shift={(3*\k,0)} 或 rotate=\a,它就能覆盖刻度线、成排的盒子,以及序列里的第 n 个元素。这样搭出来的图经得起尺寸变化;那些坐标是从预览上读下来的图经不起。
\documentclass[a4paper]{article}
\usepackage{tikz}
\usetikzlibrary{arrows.meta,positioning}
\begin{document}
% ---- 1. a scope brackets options AND coordinates: everything drawn inside
% is moved, turned and resized together, and \end{scope} stops it
\begin{tikzpicture}[node distance=14mm]
\node[draw] (one) {original};
\begin{scope}[shift={(3.4,0)}, rotate=12, scale=0.85, transform shape]
\node[draw] (two) {shifted, tilted, smaller};
\end{scope}
\draw[->] (one) -- (two);
\end{tikzpicture}
% ---- 2. scale alone moves the ink and leaves the FONTS at their size, which
% is why a scaled picture looks somehow wrong; transform shape scales
% the text as well -- and with it the line widths and the separations
\begin{tikzpicture}
\node[draw, scale=1.6] (a) at (0,0) {scale};
\node[draw, scale=1.6, transform shape] (b) at (6,0) {transform shape};
\end{tikzpicture}
% ---- 3. the unit vectors decide what (1,0) and (0,1) MEAN: this is an
% oblique coordinate system, and no re-derivation of coordinates
\begin{tikzpicture}[x={(1.6cm,0cm)}, y={(0.5cm,1.1cm)}]
\draw[help lines] (0,0) grid (3,3);
\draw[->, thick] (0,0) -- (3,0) node[right] {$\hat{x}$};
\draw[->, thick] (0,0) -- (0,3) node[above] {$\hat{y}$};
\fill (2,1) circle[radius=2pt];
\end{tikzpicture}
% ---- 4. several objects, one box: local bounding box wraps a scope in a
% rectangle node that can then be positioned, filled or arrowed at
\begin{tikzpicture}
\begin{scope}[local bounding box=g1]
\draw[thick] (0,0) circle (1);
\draw[thick] (30:1) -- (0,0) -- (0:1);
\end{scope}
\node[right=8mm of g1, align=center, font=\small]
{the whole scope\\ as one object};
\end{tikzpicture}
% ---- 5. a loop instead of a copy and paste (\foreach needs no library at all)
\begin{tikzpicture}
\foreach \a/\lbl in {0/one, 30/two, 60/three} {
\draw[->, thick, rotate=\a] (0,0) -- (1.6,0)
node[right, font=\scriptsize] {$v_{\lbl}$};
}
\end{tikzpicture}
\end{document}
当一张图拒绝编译,以及它怎么作为独立文件交付
TikZ 是一个跑在 TeX 里的解析器,所以一条消息说出的是 TeX 注意到的位置,不是你犯错的位置。五段文案承载了大多数痛。\usetikzlibrary 或 \tikzset 处的 ! Undefined control sequence.,意思是那个宏包还没加载,或者那一行坐在 \usepackage 之上。! Package pgfkeys Error: I do not know the key '/tikz/…' 是选项里的一次笔误,或者一个所属库从没加载的键。! Package tikz Error: Giving up on this path. Did you forget a ";"? 就是那个漏掉的分号,而它出现在出错那条之后的那一句上。! Package pgf Error: No shape named X is known. 说的是一个从没被创建过的名字——通常是上两行那个节点丢了它的 ;,或者那个名字住在另一个 tikzpicture 里,因为名字不跨图。而标签里的 ! Missing $ inserted. 是把 _ 或 ^ 当成普通文字写了。
真正找得到东西的顺序是:把这张图放进一个十行的文件里单独编译,注释掉一半,继续二分直到它只在一处失败;先读导言区再读坐标,因为一个缺失的库能一次解释大多数 unknown-key 的抱怨;以及先查花括号再查几何——一个缺了 } 的节点文字会让 TeX 跨语句去找那个闭合符号,这就是为什么那条消息坐在离原因四十行远的地方,也是为什么节点参数内部一个空行是同一场事故换了一张友善的脸。颜色与选项冲突也归这里:pgfplots 会替你拉进 xcolor,所以之后写 \usepackage[svgnames]{xcolor} 就产出那个眼熟的 Option clash for package xcolor,而修法是在第一次加载之前把选项交出去,而不是去跟那条消息搏斗。
一张完工的图通常想要自己的文件,而 standalone 类就是为此造的:\documentclass[tikz,border=3pt]{standalone},在 \begin{document} 里放一个 tikzpicture,本次运行就产出一个裁到墨迹的 PDF——裁得那么狠,以至画区之外的一个标签或一个箭头尖就这么没了,而 border= 就是为它存在的。在那里加载与主文档相同的字体宏包,否则嵌进来的图会用与它自己的题注不同的字母。要保持单一事实来源有两条路:编译一次,然后用 \includegraphics[width=0.62\linewidth]{figure-01} 放进那个裁切好的矢量图;或者加载 standalone 宏包并用 \import{figures/}{figure-01.tex},它用主文档的导言区来排版这张图,所以什么都不会漂移,而 mode=build 会在需要速度时退回那个已编译的 PDF。无论走哪条,最终进到档案里的图是一个矢量,而 pdftoppm 或 Inkscape 可以把栅格图交给那位坚持要栅格的人。
% ===========================================================================
% figure-01.tex -- one figure, one file, cropped to its own ink.
%
% Compiling a picture alone is also how you debug one: in a ten-line file the
% messages quoted below point at the line that caused them, which they do not
% do from inside a 60-page document.
% ===========================================================================
% border= adds a margin to the tight crop. Without it, an arrow tip or a
% label that sticks outside the drawn area is simply cut off in the PDF.
\documentclass[tikz,border=3pt]{standalone}
% Miss a letter in a library name and the run stops at:
% ! LaTeX Error: File `tikzlibrarypositioningg.code.tex' not found.
\usetikzlibrary{arrows.meta,positioning}
% Styles shared with the main document belong in a file both preambles read.
\tikzset{%
box/.style = {draw, rounded corners, minimum width=13mm, font=\small},
elab/.style = {font=\scriptsize, inner sep=1.5pt, fill=white},
>={Stealth[length=2.2mm]},
}
\begin{document}
\begin{tikzpicture}[node distance=14mm]
\node[box] (a) {sample};
% Without the positioning library the next line is not ugly, it is unknown:
% ! Package pgfkeys Error: I do not know the key '/tikz/right' ...
\node[box, right=of a] (b) {decide};
\node[box, below=of a] (c) {reject};
\draw[-{Stealth}] (a) -- node[elab, above] {$p$} (b);
\draw[-{Stealth}] (a) -- node[elab, left] {$1-p$} (c);
\draw[-{Stealth}] (b) to[bend left=14] node[elab, above, sloped] {$q$} (c);
% The four messages this picture can break on, all reported ABOVE the line
% where they belong, because TikZ is a parser running inside TeX:
% 1. lose the ";" at the end of any \draw above and the run stops at the
% NEXT statement with:
% Package tikz Error: Giving up on this path.
% 2. name a node that no statement created (usually for reason 1):
% Package pgf Error: No shape named d is known.
% 3. write x_1 in a node text without dollars:
% Missing $ inserted.
% 4. delete the positioning library above and the node placement line is
% not ugly any more, it is unknown:
% Package pgfkeys Error: I do not know the key '/tikz/right' ...
\end{tikzpicture}
\end{document}
% ===========================================================================
% main.tex -- three ways to bring that file back in, ordered by how little
% can drift between the figure and the prose around it:
% (1) compile the figure once, then place the cropped vector:
% pdflatex figure-01.tex
% \includegraphics[width=0.62\linewidth]{figure-01}
% Load the SAME font packages in both preambles or the figure arrives
% in different letters from the caption under it.
% (2) let the main document typeset the source:
% \usepackage{standalone}
% \import{figures/}{figure-01.tex}
% Same preamble, same fonts, same everything; the build option
% \usepackage[mode=build]{standalone}
% swaps in the compiled PDF for the fast pass.
% (3) share only the \tikzset block by \input-ing it from both files, so the
% styles cannot disagree even when the figures are built separately.
% ===========================================================================
本课速查
每节抽一行关键代码:点小节名跳到对应位置,代码一键复制。
\begin{tikzpicture}[node distance=22mm]
\begin{tikzpicture}
\documentclass[a4paper]{article}
\documentclass[tikz,border=3pt]{standalone}
常见错误
- 写下
right of=A却期待你设的那个间隙。那个更老的形式量的是圆心到圆心,于是可见部分是node distance减去两个节点各一半,而一个更宽的标签会把它吃掉。加载positioning并写right=of A;当你真正想对齐的确实是圆心时,用on grid。 - 忘掉结束一条路径的那个分号。TikZ 会把下一条语句继续当成当前路径的延续来读,而那句抱怨——
Package tikz Error: Giving up on this path. Did you forget a ";"?——落在比你写坏的那一行晚好几行的地方。一条路径,一个;,包括\end{tikzpicture}前面那一个。 - 用一个来自你从没加载过的库的键,并把报错读成一个 bug:没有
positioning时的right=2cm of A会得到一条来自pgfkeys的 unknown-key 消息,而\usetikzlibrary写在\usepackage{tikz}之前会得到! Undefined control sequence.缺失文件的名字是可预测的——tikzlibrarypositioning.code.tex——所以库名里的一次笔误会报成一个文件缺失。 - 用文字来给节点命名:
\node {A};然后\draw (A) -- (B);。花括号里的是内容,名字是at之前那对括号,而失败要到很晚才以Package pgf Error: No shape named A is known.现身。节点名字同样停在\end{tikzpicture};它们不在多张图之间共享。 - 把
_、^或一个裸的&直接写进节点文字。节点文字是文本模式里的 LaTeX,所以上下标需要美元符号(! Missing $ inserted.),而在matrix里 and 符号是单元格分隔符:设ampersand replacement=\&,并在单元格之间写\&。 - 用
scale=0.6缩放一张图,然后纳闷为什么字母还是那么大:几何与文字是分开的两层。加上transform shape连字形一起缩放,或者——对一张必须与题注匹配的图,更干净的做法——用x=和y=设定单位向量,按你想要的尺寸去画。同一种讲究在出口处也适用:standalone的裁切是裁到墨迹的,而一个伸出盒子之外的标签就是墨迹的边界,所以给它border=2pt或更多。
关于本课的常见问题
TikZ 里 right of=A 和 right=of A 有什么区别?
\usetikzlibrary{positioning},并在新代码里用 = 那种形式;在接手来的文件里预料到旧形式。两值形式 below=8mm and -18mm of A 加的是一个垂直方向的偏移,而 on grid 是有意回到圆心到圆心的——那正是一格一格的盒子需要对齐的时候。TikZ 为什么说 I do not know the key /tikz/…,怎么修?
\usetikzlibrary 那一行;如果那个键是你自己定义的,去检查定义它的那次 \tikzset 是否跑在使用它的那张图之前。怎么在 TikZ 节点里写一个公式而不让它排出来很小?
\frac 出来很小,\sum 把上下限留在侧面。写 $\displaystyle …$,或者用 \dfrac,或者加载 mathnodes 库、给节点加上 math 键,让它的文字按展示样式排版而不带美元符号。若好几个节点都要,就把它放进一个样式:every node/.append style={math}。记住节点内部换行需要先有 align=center 或 text width=,也记住 matrix 的单元格用 and 符号作分隔符。我能把每张 TikZ 图都放在自己的文件里、同时仍然嵌进文档吗?
\documentclass[tikz,border=3pt]{standalone} 加一个 tikzpicture,单独把它编译成一张裁到图形的 PDF,然后用 \includegraphics 放进去——一个矢量、任意宽度、数学用那个文件自己加载的那些字体。若要让主文档来管字体,就加载 standalone 宏包并用 \import{figures/}{figure-01.tex}:那个子文档由主前言排版,于是图和题注不可能不一致。把共享的 \tikzset 规范样式放进第三个文件、让两份导言区都 \input 它,想要快的那一遍时用 mode=build。带坐标轴的图该用 TikZ 画还是用 pgfplots?
\draw 命令来做注释,而两个都加载是常态。为什么我把 TikZ 图导出成独立的 PDF 时,箭头上的标签被裁掉了?
\documentclass[tikz,border=3pt]{standalone},如果标签吊在边缘之外就给它更多。如果图有一部分是整个不见了而不是被裁了,常见原因是 transform canvas,它让绘制内容逃出那张图报告为自身尺寸的那个盒子。也要在 \includegraphics 之前检查导出的 PDF:一个会重新缩放页面的查看器,可能让文件看起来裁错了,而文件其实没问题。实时演示:直接编辑 LaTeX,立刻看渲染结果
预览随输入实时更新——不妨故意写坏一次,看看报错长什么样。
继续读
同一个东西的三个入口:记法本身、讲它的那一课、以及真正用它写东西的一篇文章。