図はキャンバスではなく、記述されたリストである
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 はあなたが見ている隙間そのものではなく、片方のラベルが幅広くなれば、それは黙って隙間を食べてしまいます。positioning ライブラリの right=of A は 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)$ は A と C を通る直線へ B から下ろした垂線の足、そして ([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 まで生きます——これが、単一の図に一切触れずに文書全体の見た目を作れる条件です。順序から二つのエラーが出ます。\usepackage{tikz} より前の \tikzset は第一トークンで ! Undefined control sequence. になり、現在の名前空間に定義のないキーは完全な経路、/tikz/… を名指す pgfkeys のメッセージを生みます——打ち間違いとライブラリ不足を見分ける手がかりです。
\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}
スコープと変換:scale が拡大するのは何か
\begin{scope}[⟨options⟩] は絵の両半分を括ります。中で描かれるものは全部オプションを継承し、中の座標はグループとして動かせ、\end{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) の意味を定義するので、斜軸もアイソメトリックの立方体も再導出ではなく二行の変更になります。
もう二つの小型のスコープ道具は、早い段階で元を取ります。local bounding box=⟨name⟩ はスコープが描いたもの全部をその名前の矩形ノードへ包み、矢印と箱の一群が、配置も塗りも接続もできる一つの物になります。「この四つのノードを枠で囲むには?」への正直な答えです。そして \foreach \k in {0,…,5}——ライブラリなど一切要りません——は、繰り返しを一度で書く方法で、スコープの中で 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. は _ や ^ を素のテキストで書いた場合です。
実際にものが見つかる順序はこうです。絵を十行のファイルで単独にコンパイルし、半分をコメントアウトして、一箇所で壊れるまで二分を続け、座標を読む前にプリアンブルを読んでください——ライブラリ一個の欠けが未知のキーの訴えを一度に説明します。幾何より先に括弧を確認——ノードテキストの } が欠けると 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}の直前にあるものも含めて。 - 読んでもいないライブラリのキーを使い、そのエラーをバグとして読むこと。
positioningなしのright=2cm of Aはpgfkeysから未知キーのメッセージが出て、\usepackage{tikz}より前の\usetikzlibraryは! 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の中ではアンパーサンドがセル区切りです。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 キーを与えると、ドルなしで display スタイルで組まれます。いくつものノードで必要ならスタイルへ入れてください。every node/.append style={math} のように。ノードの中の改行には先に align=center か text width= が要ること、matrix のセルはアンパーサンドが区切りであることも思い出してください。TikZ の図をすべて別ファイルに置いて、文書には取り込めますか?
\documentclass[tikz,border=3pt]{standalone} に tikzpicture を一つ、という形で書き、単独で描画へ切り抜いた PDF にコンパイルしてから \includegraphics で置きます。ベクトルなので任意の幅で使え、数学はそのファイルが読むフォントで入ります。フォントの主導権を主文書に持たせたいなら standalone パッケージを読み込んで \import{figures/}{figure-01.tex}。サブドキュメントは主プリアンブルで組まれるので、図とキャプションが食い違いようがありません。共有の \tikzset による見た目の約束は三つ目のファイルに置いて両方のプリアンブルで \input し、速い方が欲しいときは mode=build を使います。軸のあるグラフを TikZ で描くべきですか、pgfplots を使うべきですか?
\draw コマンドを平気で受け取り、両方読むのが普通です。TikZ の絵を standalone PDF として書き出すと矢印のラベルが切れます。なぜですか?
\documentclass[tikz,border=3pt]{standalone} の形で、ラベルが縁から出ていればもっと大きくします。切れるのではなく絵の一部が完全に消えるなら、よくある原因は transform canvas で、これは描画が絵自身サイズとして報告する箱から脱走できてしまいます。\includegraphics する前に書き出した PDF も確認してください。ページを拡して表示するビューアだと、ファイルは正常なのに切り抜きが間違っているように見えます。ライブ playground:LaTeX を編集して即描画
入力すると即座にプレビューが更新されます。わざと壊してエラーの見た目も確認しましょう。
続けて読む
同じ話題への三つの入口:記法そのもの、それを教える課、そして実際に使っている記事。