A plot as source, and the compat line
\usepackage{pgfplots} loads TikZ (and therefore PGF) and adds a plotting layer on top of it: an axis environment that knows about coordinate systems, tick placement, number formatting, legends and colour maps. The consequence for a document is the same one as for every other source-drawn object: the figure is versioned with the text, its labels are set in the document font at the document size, it regenerates identically on another machine, and a change to the data is a diff rather than a re-export.
The first line after the package should be \pgfplotsset{compat=1.18}, and it is not a formality. pgfplots changed the placement rules for axis labels, tick labels and legends several times in its history, and the compatibility level selects the behaviour of that release so that an old document keeps looking the way its author left it. Without a compat setting the log says so — "Please, at least set compatibility version 1.3 or newer" — and the axis is drawn with the pre-1.3 label rules, which is why labels sit in odd places in old sources that were never updated.
Use an explicit version, not compat=newest. The latter is a promise that your figure will follow every future change in label geometry, and it is the reason a thesis recompiled years later has axis labels in different positions. Set it once in the preamble of the main file; in a project of standalone figures, put it in a shared style file so a per-figure compat cannot disagree with the document.
One boundary worth stating: pgfplots is for plots — something with a coordinate system and numbers on the axes. A schematic, a flow diagram or a circuit is TikZ or a domain-specific library, and forcing a schematic through axis produces a worse picture and a slower build.
Anatomy of the axis environment
Two pairs of keys define what part of the plane you see. xmin/xmax/ymin/ymax fix the visible range; domain (and ydomain, zdomain for three dimensions) fixes the range over which a function is evaluated. They are different things and it is routine to set one without the other: give domain=0:5 with xmax=10 and the curve stops in mid-air, which is a legitimate way to draw a truncated model but looks like a bug when it is accidental.
Sizing is width=, height= and scale only axis. By default a width request is the width of the whole printed box, tick labels and rotated y-label included, so two plots with the same width but different label lengths end up with different data widths. scale only axis=true moves the request onto the axis box itself, which is what you need for panels that must line up; the alternative is a fixed xlabel style/ylabel style and the discipline to keep label lengths equal.
Ticks are the third group: xtick={0,2,...,12} (the ... step syntax is pgfplots' own, evaluated at typeset time), ytick pos=left, minor tick num=4, tick align=inside|outside|center, tick style={...}, and label formatting through xticklabel style={/pgf/number format/.cd,fixed,precision=2}. A label you write yourself is xticklabel={\tick, \ticknum}-style code: \tick is the value and \ticknum the index, so xticklabel={\pgfmathprintnumber{\tick}\,ms} appends a unit without scaling the data.
The remaining keys are about how the frame looks and what sits in front of what: axis lines=left|middle|center|box|none, axis background/.style={fill=gray!5}, grid=major with grid style, enlargelimits=0.05 to add margin so points are not on the border, clip=false when a curve should visibly continue past the frame, and axis on top, which draws the frame and ticks over the plots — the option to set when a dense curve currently hides your tick labels.
\log_{10} y = \log_{10} a + b\,\log_{10} x \qquad (y = a\,x^{b})
width and height once through \pgfplotsset{...} as a house style; per-figure size requests are the reason a supplement looks like eleven different documents.Three ways to give addplot something to draw
\addplot {⟨expression⟩} evaluates a mathematical expression in the axis coordinate system. The language is pgf's, not TeX's: multiplication is *, powers are ^, functions are sin, cos, exp, ln, sqrt, abs, mod — and, crucially, the trigonometric functions take radians unless you wrap the argument in deg( ) or set the trig format plots=rad style. cos(3*x) silently draws the wrong thing in a document whose author thought in hertz.
\addplot coordinates {(0,0) (1,1.2) (2,1.9)} takes an explicit point list — the right form for three or four measured points, and the wrong form for anything else, because the list is parsed by TeX and becomes slow and unreadable. For a real dataset, \addplot table {file.dat}, which is the subject of the next section.
The third form matters for how styles combine. \addplot[blue,dashed]{...} replaces the plot style, so the axis' colour cycle is skipped and your second plot is the same colour as the first; \addplot+[mark=none]{...} appends to it, keeping the cycle. The + is a single character and it is the most common reason a two-curve plot comes out in one colour.
Anything else is a plot handler: \addplot gnuplot {\x**2} hands the expression to an external gnuplot (it needs --shell-escape and the gnuplot binary), raw gnuplot lets you write gnuplot source verbatim, and \addplot graphics [xmin=...,xmax=...,ymin=...,ymax=...] {scan.png} overlays a scanned chart so that its pixels can be read against the coordinate system — a legitimate use when the original data of an old figure is gone.
\documentclass[a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18} % without this the labels use old positions
% A house style: every axis in the document gets the same size and font.
\pgfplotsset{%
width=0.75\textwidth, height=0.55\textwidth,
label style={font=\small}, tick label style={font=\small},
every axis plot post/.append style={thick},
}
\begin{document}
\begin{figure}[htbp]
\centering
\begin{axis}[
title={Damped oscillator},
xlabel={time $t$ [s]},
ylabel={displacement $x$ [mm]},
xmin=0, xmax=12,
ymin=-1.2, ymax=1.2,
xtick={0,2,...,12},
ytick={-1,-0.5,0,0.5,1},
grid=major,
grid style={dotted, black!25},
legend pos=outer north east,
axis lines=left,
enlargelimits=false,
]
\addplot[domain=0:12,samples=201,smooth,blue]
{exp(-0.4*x)*cos(deg(3*x))};
\addlegendentry{$\mathrm{e}^{-0.4t}\cos 3t$}
\addplot[domain=0:12,samples=201,densely dashed,black!60]
{exp(-0.4*x)};
\addlegendentry{envelope}
\addplot[only marks,mark=*,mark size=1.4pt,red!70!black]
coordinates {(0.5,0.92) (2.1,-0.41) (4.0,0.12) (7.3,-0.05)};
\addlegendentry{measured}
\end{axis}
\caption{Simulation against the four measured points.}
\label{fig:decay}
\end{figure}
\end{document}
Data files, columns and error bars
A data file is whitespace-separated by default: each row is x y (or x y z, or more columns), and \addplot table {data.dat} takes the first two columns. You select explicitly with \addplot table [x=time, y=flow] {data.csv}, and the separator is a table option: col sep=comma|semicolon|tab|space|ampersand. A comma-separated export silently becomes one enormous column without that option, and the error message is unhelpful, so check the separator before the file.
Read a file once and refer to the handle afterwards: \pgfplotstableread[col sep=comma]{flow.csv}\flowdata then table[x=time,y=flow]{\flowdata} in several plots. It is faster, and it guarantees that two panels really are the same data. The column set can be extended at read time with \addplot table [create col/expr={\thisrow{a}/\thisrow{b}}], which computes a derived column without a preprocessing step.
Error bars are a plot option rather than a separate plot: \addplot+[only marks,error bars/.cd,y dir=both,y explicit] followed by a table with a y error column (or y const error for a single value, or y relative*100 for percentages). In coordinates form the errors are written inline, coordinates {(1,2) +- (0.1,0.05)}, which is a common source of confusion — +- is relative to the point, and +-* is absolute. A plot with y dir=both draws caps at both ends of the bar.
Missing and out-of-range values need an explicit policy. An empty field or nan terminates the line segment by default; unbounded coords=jump is the option that keeps the rest of the curve and leaves a visible gap, and restrict x to domain=0:10 filters data rather than clipping the view. Combining const plot (a step function, correct for binned counters) with const plot mark left|right is how a histogram of irregular bins stays honest.
\varepsilon_{i} = \sqrt{\varepsilon_{\mathrm{stat},i}^{2} + \varepsilon_{\mathrm{syst},i}^{2}}
\documentclass[a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usepackage{filecontents}
\begin{filecontents*}{flow.csv}
time,valve,flow,error
0.0,0.0,1.02,0.04
2.5,0.5,1.44,0.05
5.0,1.0,1.98,0.06
7.5,1.5,2.61,0.09
10.0,2.0,3.40,0.15
\end{filecontents*}
\begin{document}
% Read once, reuse in several plots; nothing is parsed at typeset time.
\pgfplotstableread[col sep=comma]{flow.csv}\flowdata
\begin{figure}[htbp]
\centering
\begin{axis}[
xlabel={time [s]}, ylabel={flow [L/min]},
xmin=0, xmax=10, ymin=0.8, ymax=3.8,
grid=both, grid style={line width=0.2pt, draw=gray!30},
tick align=outside, tick style={black},
scaled ticks=false,
yticklabel style={/pgf/number format/fixed},
legend style={at={(0.03,0.97)},anchor=north west,draw=none},
]
\addplot+[only marks,error bars/.cd,y dir=both,y explicit]
table[x=time,y=flow,y error=error]{\flowdata};
\addlegendentry{runs}
\addplot+[thick,smooth] table[x=time,y=flow]{\flowdata};
\addlegendentry{guide for the eye}
\end{axis}
\caption{Measured flow with the statistical error of each point.}
\end{figure}
\end{document}
Curves, marks and the colour cycle
Plot styles are named and reusable: \pgfplotsset{myline/.style={thick,blue!60!black,mark=*}} at the document level, then \addplot[myline]. Styles nest, so a house style of every axis plot post/.append style={thick} changes every plot in the document without touching a single figure, which is the way to fix a line weight after forty figures have been written.
The cycle list assigns colours and marks automatically. cycle list name=colorful (or mark list, group plot list, rgb) replaces the default, and a custom one is a list of style fragments. If a plot needs to be excluded from the cycle, give it an explicit color= and it stops consuming the next entry — which is how you keep a "theory curve is always black" convention.
smooth deserves a warning: it applies a spline through the computed points, so with a low samples value it invents curvature between them. samples=20,smooth on a sharply peaked function is not a smoother curve, it is a different function. Increase samples rather than trusting smooth, and for data points never use it at all: a line interpolated between measurements is a claim.
For a curve that is wrong in the middle of a range, look at restrict expr to domain, at a singularity (an expression that divides by zero at x=0 draws a spike across the plot), and at samples near the peak: an oscillating function needs enough samples per period, so domain=0:100 with samples=100 aliases. The rule of thumb is a few hundred evaluations per visible oscillation.
x_{i} = a + i\,\frac{b-a}{N-1}, \qquad i = 0,\dots,N-1
Legends, titles and annotations
A legend entry is emitted after the plot it describes: \addplot ...; \addlegendentry{...}. Inside \nextgroupplot panels and in \addplot+[] chains the same order applies, and forgetting the ; at the end of an \addplot is the error that follows.
Placement is either a keyword — legend pos=north east, south west, outer north east (outside the frame, the option that stops a legend eating the data) — or full control through legend style={at={(0.5,-0.18)},anchor=north,legend columns=-1,draw=none}, where the coordinate is in the axis' own relative system and legend columns=-1 lays the entries out horizontally. For a shared legend under a row of panels, legend to name=legA inside each axis and \ref{legA} in the surrounding TikZ picture is the mechanism.
Titles and axis labels are ordinary text with ordinary maths: xlabel={time $t$ [s]} and, if a label must move, xlabel style={at={(0.5,-0.2)},font=\small} or the simpler xlabel shift/ylabel shift. That label geometry is precisely what compat controls, which is why an unset compatibility level shows up first as "my y-label is on top of the ticks".
Annotation is where a figure becomes an argument. Inside the axis you can draw with the axis coordinates directly: \draw[gray,dashed] (axis cs:3.2,0) -- (axis cs:3.2,1.1);, place a node at (axis cs:3.2,1.1) {threshold}, and mark a regression with \addplot using table [y expr={...}]. The axis cs: prefix is not optional in a groupplot or when a \tikzset coordinate system is in scope — a bare (3.2,0) is in the surrounding picture, not the axis, and the node lands in the wrong figure.
Panels that belong together: groupplots
Two side-by-side axes drawn as two axis environments in two minipages give you two independent geometries: different tick-label widths mean the plot boxes do not line up, and the vertical separation is whatever the minipage happened to leave. The groupplots library (\usepgfplotslibrary{groupplots}) replaces that with one groupplot environment whose group style knows the cell layout: group size=2 by 2, horizontal sep=14mm, vertical sep=15mm, and the very useful yticklabels at=edge left, xlabels at=edge bottom, ylabels at=edge left so that only the outer panels carry labels.
Each panel starts with \nextgroupplot[⟨options⟩], which takes every key a plain axis takes. Shared limits are set on the groupplot options and overridden per panel; \nextgroupplot[group/inner pos=...] and \nextgroupplotempty cover sparse layouts, and a panel that must span two cells is a group style geometry question rather than a minipage hack.
Grouping is also the point at which data reuse pays: read the table once before the environment, then refer to the same handle in four panels with different column mappings. If two panels must share a colour, give it explicitly rather than relying on the cycle continuing across the panel boundary — the cycle resets per \nextgroupplot in some configurations and the coupling is not worth keeping.
The cost of drawing figures in TeX is real and worth knowing before a reviewer complains: pgfplots evaluates and typesets every point inside the TeX run, so a figure with 100 000 points or a document with sixty plots can take minutes. The answers, in order: downsample the data file, keep samples as low as the curve tolerates, and externalise with the TikZ external library (\usetikzlibrary{external} plus \tikzexternalize[prefix=tikz-cache/]), which caches each picture as its own PDF and redraws only what changed. For a plot with a million points, generate a PDF elsewhere and include it — the source-drawn rule is for figures whose numbers appear in the text, not for stress-test data.
\bar{y} = \frac{1}{n}\sum_{i=1}^{n} y_{i}, \qquad s^{2} = \frac{1}{n-1}\sum_{i=1}^{n}(y_{i} - \bar{y})^{2}
\documentclass[a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usepgfplotslibrary{groupplots}
\begin{document}
\begin{figure}[htbp]
\centering
\begin{groupplot}[
group style={group size=2 by 2,
horizontal sep=14mm, vertical sep=15mm,
yticklabels at=edge left,
ylabels at=edge left,
xlabels at=edge bottom},
width=0.42\textwidth, height=0.34\textwidth,
grid=major, thick,
]
\nextgroupplot[title={(a) linear}, xmin=0, xmax=5,
ylabel={$f$ [a.u.]}]
\addplot {exp(-0.5*x)*cos(deg(2*x))};
\nextgroupplot[title={(b) log scale}, xmin=0.1, xmax=100,
xmode=log, ymode=log,
ylabel={$|H(f)|$}]
\addplot {1/(x+1)};
\nextgroupplot[title={(c) cumulative}, xlabel={$x$ [mm]}]
\addplot {0.5*(1+erf(x-1))};
\nextgroupplot[title={(d) scatter}, xlabel={$x$ [mm]},
only marks, mark size=1pt]
\addplot+[] {rnd + 0.2*x};
\end{groupplot}
\caption{Four views of the same model, drawn as one object.}
\label{fig:group}
\end{figure}
% Compile cost is real: externalise if the document has many such figures.
% \usetikzlibrary{external}
% \tikzexternalize[prefix=tikz-cache/]
% The first run after a change redraws only the affected figure.
\end{document}
Log axes, ticks and the errors that follow
xmode=log and ymode=log switch the axis to a logarithmic scale, with log basis x=10 (or 2) as the base and decade ticks generated automatically; log ticks with simply numbers replaces the 10ⁿ notation when the reader prefers plain values. A power law y = a x^b becomes a straight line on log-log paper, which is the honest way to show an exponent, and ymode=log over three decades is what makes a decay curve readable at late times.
A log axis cannot contain zero: the first symptom is WARNING: "ymin=0" is not allowed in log coordinates or an axis that draws nothing. Set the lower limit to the smallest positive value you care about, and filter zeros out of the data with restrict y to domain=1e-3: rather than letting them reach the axis.
The three errors that appear at compile time are consistent. Package pgfplots Error: Could not parse input '...' is a bad expression or a data file the separator options do not match. Sorry, an error occurred in the plot description: 'No valid input was found' means the table columns are not what x=/y= named. And a \begin{axis} that produces Environment axis undefined is the package not being loaded or, more often, pgfplots being loaded after a class or package that expects it first — beamer and tikz overlays are the usual culprits.
The silent one is a scale mismatch: with compat unset the labels move, with scale only axis unset the panels do not align, and with enlargelimits left at its default the data does not touch the frame, so two plots of the same range look different. Set all three once in a \pgfplotsset block and every subsequent figure is comparable to the last.
Lesson cheat sheet
One key line of code from each section — jump to it or copy it straight from here.
\log_{10} y = \log_{10} a + b\,\log_{10} x \qquad (y = a\,x^{b})
\documentclass[a4paper]{article}
x_{i} = a + i\,\frac{b-a}{N-1}, \qquad i = 0,\dots,N-1
Common mistakes
- Leaving
\pgfplotsset{compat=...}out, or usingcompat=newest: label geometry then depends on the installed version and old figures move when the distribution is updated. - Writing
\addplot[blue]{...}for every curve instead of\addplot+[...]: the+is what keeps the colour cycle running, and without it three curves are one colour. - Using
cos(2*x)and expecting hertz: pgfplots trigonometric functions take radians unless the argument is wrapped indeg(...). - Confusing
domainwithxmin/xmax: the first is where the function is evaluated, the second is what the axis shows, and a curve that stops in mid-page is the usual symptom. smoothwith a smallsamplesvalue: the spline interpolates the points you gave it, so it manufactures structure that is not in the data.- Assuming a comma-separated file will be read: without
col sep=commaevery row is one column and the plot is empty or wrong. - Setting
ymin=0on aymode=logaxis, or laying out a multi-panel figure with minipages and then fighting to align the axes.
Questions about this lesson
How do I plot a function in LaTeX without another program?
\begin{axis} with xmin/xmax/ymin/ymax plus \addplot[domain=0:5,samples=100]{exp(-x)};. The expression is evaluated by TeX at compile time, so the curve, its labels and your text all use the same font, and the figure regenerates whenever the source changes.What does pgfplotsset compat do?
How do I plot data from a CSV file with pgfplots?
\pgfplotstableread[col sep=comma]{data.csv}\data, then \addplot table [x=time, y=flow] {\data};. Name the columns rather than counting them, and keep the header row: pgfplots reads column names as keys. Whitespace-separated files need no separator option at all.Why is my pgfplots legend in the way of the data?
How do I add error bars to a pgfplots curve?
pgfplots or matplotlib for a paper figure?
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.