The picture is a listing, not a canvas
TikZ changes one thing and everything else follows: a diagram is described rather than dragged. Its nodes, coordinates, arrows and colours are lines in the same file as the prose, so the figure takes part in version control, a diff shows what was changed, a rebuild cannot quietly produce a different picture from the one that was reviewed, and there is no selection tool to lose or a final_final_v3.png to hunt for. The text inside a node is typeset by the same TeX that typesets the sentence above it, which is why a TikZ figure never looks pasted in.
Under the syntax there are two layers. PGF is the low-level key and path machinery; TikZ is the readable front end you actually type, and \usepackage{tikz} loads PGF and asks it which graphics driver is in use — pdftex.def, luatex.def, dvips.def, dvisvgm.def. That indirection is the reason one source becomes a PDF, a PostScript file or an SVG without a single edit, and it is also why colour and transparency travel further under lualatex and xelatex than under the oldest engine. Extra behaviour is not built in, it is loaded: \usetikzlibrary{positioning,calc,arrows.meta} pulls in one file per group of keys, and forgetting that line is the origin of a large share of TikZ error messages.
What you pay is the loop: you compile in order to see. Nothing moves while you drag, because there is nothing to drag, and a coordinate that is wrong stays wrong until the next run. The first diagram takes an hour; the twentieth takes minutes, because the vocabulary is finite and fixed — a node, a path, an option list, a style, a library. It is worth knowing the border of the tool early as well: TikZ draws pictures, and pgfplots draws plots. A figure with numbers on two axes is the other package's job, because it computes the scales, the tick positions and the legend from the data instead of from your patience.

Nodes, coordinates and the maths inside them
A node has four parts and only one of them is mandatory: \node[⟨options⟩] (⟨name⟩) at (⟨coordinate⟩) {⟨text⟩}; — the name is the parenthesised bit, not the text, and \draw (A) -- (B); only works if those parentheses were written. A \coordinate (O) at (0,0); is a name with no ink at all, which is how you mark a midpoint you will connect later without anything appearing. The other form to learn on day one is a node at the end of a path: \draw (0,0) -- (2,1) node[midway, above] {f}; places the label on the segment it follows, and it is the same construction that puts text beside an arrow.
Every node is a box, and a box has named points: (A.center), (A.north), (A.south west), the border anchors of the shape it draws, and for a circle an angle — (A.30) is the point thirty degrees round from the centre. The anchor= option then chooses which of those points is put on the coordinate you gave, which is why the same \node line can land two centimetres away from where you expected. Coordinates are pairs in centimetres by default, so (2,3) means 2cm right and 3cm up, and what a unit means is itself adjustable through x= and y=.
Node text is ordinary LaTeX in horizontal mode, and that is the whole reason TikZ beats an image editor for mathematical figures: an integral in a node is typeset by the engine, in the document font, at the document size. Three consequences bite early. Maths needs its own dollars, so \node {x_1} ends in ! Missing $ inserted. while the same content between dollars is fine — and dollars inside a node give you text-style maths, which is the small fraction and the side-sitting limits in the block below; \displaystyle, \dfrac, or the math key from the mathnodes library is the fix. A line break inside a node needs align=center or text width= first. And in a matrix the ampersand is the cell separator, so a cell holding its own alignment needs 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}
Paths: what draw, fill and the semicolon actually do
Everything visible in a picture is a path: a list of operators — -- for a straight segment, -| and |- for a corner, to[bend left] and .. controls .. .. for curves, circle, rectangle, arc, grid — with nodes allowed anywhere in the list. A path is executed only by the semicolon that closes it. Until then nothing exists on the page, which is why a label can be written in the middle of a line and why a missing ; never reports on the line that missed it.
The prefix says what happens to the finished path: \draw strokes it, \fill paints its interior, \filldraw does both and the order of the two matters where they overlap, \shade fills it with a gradient, and plain \path computes the geometry and paints nothing — the usual way to drop a \coordinate or a label where no line should appear. The look lives in the option list: line width=0.6pt and its named steps from ultra thin to ultra thick, dashed, densely dotted, dash pattern=on 2pt off 3pt, rounded corners=2pt, line cap=round, opacity=0.4, and colours mixed with an exclamation mark such as red!40!black, which needs nothing beyond TikZ itself.
Options may be changed in the middle of a path — \draw[thick] (0,0) -- (1,1) [dashed] -- (2,1); — which is how a connector stays solid where it is real and goes dashed where it is hypothetical. -| and |- are the two-segment corner that routes an edge around a box instead of through it, and to[out=20,in=160] is a Bézier with angles you can read rather than with two control points you have to imagine. This is also the section where two mistakes are made: a forgotten ;, and a brace or bracket left open, which sends TeX looking for the closing token across the rest of the picture. Both produce an error whose line number is not the line you broke.
% 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 and calc: distances that mean what they say
Two boxes and an arrow between them is the most repeated construction in the language, and there are two syntaxes for it with different geometry underneath. right of=A is the original TikZ 0.x form — still accepted, still in every old answer on the net — and it measures centre to centre, so node distance is not the gap you see and a wider label quietly eats it. right=of A, from the positioning library, measures from A's east border anchor to the new node's west border anchor: the gap is the distance you wrote, whatever the text inside either box. If a listing you inherited looks like the first one on this page, that is what it is doing.
The rest of positioning is the same idea with more directions: below left=of A for the diagonal, right=2cm of A to override one distance for one node, and the two-value form below=8mm and -18mm of A, where the second number is the perpendicular offset and a negative value flips the direction. on grid brings centre-based placement back on purpose: distances are then measured between centres again, but the centres are snapped to a shared grid, which is what makes a lattice of boxes line up. node distance=14mm sets the default for the whole picture, and every single placement may override it for itself, which is the usual way to keep one pair of boxes tighter than the rest.
calc is the other half of not doing geometry by hand. $(A)!0.5!(B)$ is the midpoint, $(A)!1.6!(B)$ continues the line past B, $(A)!0.5!90:(B)$ is that midpoint turned ninety degrees about A, $(A)!(B)!(C)$ is the foot of the perpendicular from B onto the line through A and C, and ([xshift=-3pt]A.north west) shifts any coordinate at all, an anchor included. With let you read measurements back out — \path let \p1 = ($(Q)-(P)$), \n1 = {veclen(\x1,\y1)} in gives the distance between two nodes as a length you can print or use. Both key sets are libraries: without \usetikzlibrary{positioning,calc} the = form is not merely ugly, it does not exist, and the pgfkeys complaint names the key it could not find.
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, labelled edges and where maths does it better
An arrow is a path with tips: [->], [<-], [<->], and the default tip is deliberately plain. The maintained library is arrows.meta, whose names are Stealth, Latex, Triangle, Circle and Bar, written inside brackets when they need options — [-{Stealth[length=2.4mm]}], [-{Triangle[angle=60:3pt]}] — and with >=Stealth you set what a plain -> means for the rest of the picture or, in the preamble, of the document. The older arrows library, which you will meet in nearly every archived answer, uses lower-case names and a trailing prime to reverse a tip: [stealth'-]. It predates arrows.meta and cannot configure a tip's size, which is why new files should write the new names.
A label on an edge is a node on the path, so the placement keys are the ones from the previous sections: midway, near start, pos=0.65 for how far along; above, below, left, right for which side; and sloped, which rotates the text to follow a line that is not horizontal. A label that sits on top of a line needs a background or the stroke reads through the glyphs — fill=white, inner sep=1.5pt is the two-key knockout, and font=\scriptsize keeps labels smaller than the nodes they annotate. Two arrows between the same pair of boxes are one path with bend left=16, and edge[bend left] lets a branch leave the path you are building and come back to it.
In running text, though, TikZ loses. A tikzpicture is a box that does not know the baseline of the line it lands on until you tell it with baseline=(A.base), and it will not stretch or shrink with the surrounding maths. So an arrow that belongs to an equation stays in the equation: \xrightarrow{f} from amsmath puts the label above the shaft, keeps the line's own baseline, and scales with the size of the surrounding formula. The rule that keeps both looking right is short: use a picture for geometry, and maths for notation.
A \hookrightarrow B \twoheadrightarrow C \qquad x \longmapsto \varphi(x)
amsmath arrow joins the baseline it is written on, which is exactly the work an inline picture has to be told to do.\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}
Styles, tikzset and every node: one look for the document
Repeating draw, thick, rounded corners=2pt, minimum width=14mm on thirty nodes is a promise you will break on the thirty-first. A style turns that list into a name: base/.style={…} inside \tikzset installs a key in the /tikz/ namespace, styles compose by naming another style inside their own list, and base/.append style={minimum height=8mm} refines one without rewriting it — which is how a journal class adjusts a house style it did not write. .style args={#1,#2} takes arguments, called as [tint={red,14}], and covers the colour variants you would otherwise enumerate by hand.
The second half is the styles you never invoke: every node/.style and its relatives every picture, every path, every edge, every pin. They reach the nodes nobody remembered to tag, which is the difference between one consistent figure and a figure with thirty nodes and four label sizes. font=, inner sep=, outer sep= and the minimum size= family belong there, because they are the settings a reviewer asks for globally, and because a size key is only a lower bound: a node holding more text than minimum width grows, so a style is also where you put align= or text width= to stop that growth.
Lifetime decides where an option goes, and this is the part that prevents surprises. Options on \begin{tikzpicture}[…] reach every path in that picture and stop at its \end{tikzpicture}; options on a scope stop at its \end{scope}; a \tikzset in the preamble lives until the next \tikzset, which is what makes a document-wide look possible without touching a single figure. Two errors come from the order: \tikzset before \usepackage{tikz} is an ! Undefined control sequence. at the first token, and a key that is not defined in the current namespace produces a pgfkeys message that names the full path, /tikz/… — which is how you tell a typo from a missing library.
\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}
Scopes, transforms and the canvas: what scale scales
\begin{scope}[⟨options⟩] brackets both halves of a picture. Everything drawn inside inherits the options, the coordinates inside can be moved as a group, and \end{scope} ends the effect — nesting is normal, and in a forty-node diagram a scope is how you keep one experiment from recolouring the rest. The keys are the ordinary transform set: shift={⟨coordinate⟩}, xshift=, yshift=, rotate=⟨deg⟩, rotate around={⟨angle⟩:(⟨point⟩)}, scale=, xscale=, yscale=, xslant=, and the raw cm= matrix for anything the named keys cannot express.
The one that surprises everybody once: scale transforms the geometry, and text is not geometry. A scaled node keeps its font size, so the picture comes out with bigger boxes and small letters unless you add transform shape — which then scales the text, the line widths and the separations together, which is not always what you wanted either. transform canvas is the third level: it transforms the coordinate system itself, lets drawing land outside the region the picture reports as its own box, and is how ink can go missing near a page margin. For unit changes that are not distortions, set x=, y= and z=: those three define what (1,0) and (0,1) mean, which turns an oblique axis or an isometric cube into a two-line change instead of a re-derivation.
Two smaller scope tools pay for themselves early. local bounding box=⟨name⟩ wraps everything a scope drew in a rectangle node of that name, so a group of arrows and boxes becomes one thing you can position, fill or connect — the honest answer to the question "how do I draw a frame around these four nodes". And \foreach \k in {0,…,5}, which needs no library at all, is how a repetition is written once: with shift={(3*\k,0)} or rotate=\a inside a scope it covers ticks, rows of boxes, and the nth element of a series. A picture built this way survives a change of size; a picture whose coordinates were read off a preview does not.
\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}
When a picture refuses to compile, and how it ships as its own file
TikZ is a parser running inside TeX, so a message names the place TeX noticed, not the place you erred. Five texts carry most of the pain. ! Undefined control sequence. at \usetikzlibrary or \tikzset means the package is not loaded yet, or the line sits above the \usepackage. ! Package pgfkeys Error: I do not know the key '/tikz/…' is a typo in an option or a key whose library was never loaded. ! Package tikz Error: Giving up on this path. Did you forget a ";"? is the missing semicolon, arriving at the statement after the one at fault. ! Package pgf Error: No shape named X is known. means a name that was never created — usually the node two lines up lost its ;, or the name lives in a different tikzpicture, since names do not cross pictures. And ! Missing $ inserted. in a label is _ or ^ written as plain text.
The order that actually finds things: compile the picture on its own in a ten-line file, comment half of it out and keep bisecting until it breaks in one place, read the preamble before the coordinates because a missing library explains most unknown-key complaints at once, and check braces before geometry — a node text whose } is missing makes TeX hunt across statements, which is why the message sits forty lines from the cause, and why a blank line inside a node argument is the same accident with a friendlier face. Colour and option clashes belong here too: pgfplots pulls xcolor in for you, so \usepackage[svgnames]{xcolor} after it produces the familiar Option clash for package xcolor, and the fix is to hand the options over before the first load rather than to fight the message.
A finished figure usually wants its own file, and the standalone class is made for it: \documentclass[tikz,border=3pt]{standalone}, one tikzpicture inside \begin{document}, and the run produces a PDF cropped to the ink — cropped so hard that a label or an arrow tip outside the drawn area is simply gone, which is what border= is for. Load the same font packages there as in the main document or the included figure arrives in different letters from its own caption. For one source of truth there are two routes: compile once and \includegraphics[width=0.62\linewidth]{figure-01} the cropped vector, or load the standalone package and \import{figures/}{figure-01.tex}, which typesets the figure with the main document's preamble so nothing can drift, with mode=build falling back to the compiled PDF for speed. Either way the figure that reaches the archive is a vector, and pdftoppm or Inkscape can hand a raster to whoever insists on one.
% ===========================================================================
% 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.
% ===========================================================================
Lesson cheat sheet
One key line of code from each section — jump to it or copy it straight from here.
\begin{tikzpicture}[node distance=22mm]
\begin{tikzpicture}
\documentclass[a4paper]{article}
\documentclass[tikz,border=3pt]{standalone}
Common mistakes
- Writing
right of=Aand expecting the gap you set. That older form measures centre to centre, sonode distanceminus half of each node is what remains visible, and a wider label eats it. Loadpositioningand writeright=of A; useon gridwhen centres really are the thing you want aligned. - Forgetting the semicolon that ends a path. TikZ goes on reading the next statement as a continuation of the current path, and the complaint —
Package tikz Error: Giving up on this path. Did you forget a ";"?— lands lines later than the line you broke. One path, one;, including the one before\end{tikzpicture}. - Using a key from a library you never loaded, and reading the error as a bug:
right=2cm of Awithoutpositioninggives an unknown-key message frompgfkeys, and\usetikzlibrarybefore\usepackage{tikz}gives! Undefined control sequence.Names of the missing files are predictable —tikzlibrarypositioning.code.tex— so a typo in a library name reports as a missing file. - Naming a node by its text:
\node {A};then\draw (A) -- (B);. The braces are content, the name is the parenthesis beforeat, and the failure appears much later asPackage pgf Error: No shape named A is known.Node names also stop at\end{tikzpicture}; they are not shared between pictures. - Putting
_,^or a bare&straight into node text. Node text is LaTeX in text mode, so subscripts need dollars (! Missing $ inserted.), and inside amatrixthe ampersand is the cell separator: setampersand replacement=\&and write\&between the cells. - Scaling a picture with
scale=0.6and wondering why the letters stayed large: geometry and text are separate layers. Addtransform shapeto scale the glyphs too, or — cleaner for a figure that must match its caption — set the unit vectors withx=andy=and draw at the size you want. The same care applies on the way out: astandalonecrop is cut to the ink, and a label that sticks past the boxes is the ink's edge, so give itborder=2ptor more.
Questions about this lesson
What is the difference between right of=A and right=of A in TikZ?
\usetikzlibrary{positioning} and use the = form in new code; expect the old form in inherited files. The two-value form below=8mm and -18mm of A adds a perpendicular offset, and on grid goes back to centre-to-centre on purpose, when a lattice of boxes has to line up.Why does TikZ say I do not know the key /tikz/… and how do I fix it?
\usetikzlibrary line in the preamble; if the key is one you defined yourself, check that the \tikzset that defines it runs before the picture that uses it.How do I write a formula inside a TikZ node without it coming out tiny?
\frac comes out small and \sum keeps its limits at the side. Write $\displaystyle …$ or use \dfrac, or load the mathnodes library and give the node the math key so its text is set in display style with no dollars. If several nodes need it, put it in a style: every node/.append style={math}. Remember that a line break inside a node needs align=center or text width= first, and that a matrix cell uses the ampersand as its separator.Can I keep every TikZ figure in its own file and still include it in the document?
\documentclass[tikz,border=3pt]{standalone} with one tikzpicture, and compile it alone to a PDF cropped to the drawing, then place it with \includegraphics — a vector, at any width, with the maths in whatever fonts that file loads. To keep the main document in charge of fonts instead, load the standalone package and use \import{figures/}{figure-01.tex}: the subdocument is typeset by the main preamble, so figure and caption cannot disagree. Put the shared \tikzset house style in a third file that both preambles \input, and use mode=build when you want the fast pass.Should I draw a plot with axes in TikZ or use pgfplots?
\draw commands for annotations, and loading both is normal.Why are my arrow labels cut off when I export a TikZ picture as a standalone PDF?
\documentclass[tikz,border=3pt]{standalone}, and give it more if labels hang off the edges. If part of the picture is missing rather than clipped, the usual cause is transform canvas, which lets drawing escape the box the picture reports as its own size. Check the exported PDF before \includegraphics as well: a viewer that rescales the page can make it look as though the crop were wrong when the file is fine.Live playground: edit the LaTeX, see it render
The preview updates as you type — break it on purpose to see how errors look.
Keep reading
Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.