Plots in LaTeX with PGFPlots
PGFPlots draws charts inside your document from a formula or a data file. The axes and labels use the same fonts as your text, and the charts stay sharp when printed. This guide covers line plots, plots from CSV files, bar charts and the settings that make them readable.
Setup
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}compat fixes the behaviour to a known version, so a later update does not change how your charts look. PGFPlots loads TikZ for you.
A first plot
\begin{tikzpicture}
\begin{axis}[xlabel={$x$}, ylabel={$f(x)$}]
\addplot[blue, thick, domain=-2:2, samples=100] {x^2};
\end{axis}
\end{tikzpicture}axis draws the frame, ticks and labels; each \addplot adds a curve. domain is the x range and samples the number of points computed. Trigonometric functions take degrees, so write sin(deg(x)) for x in radians.
Several curves and a legend
\begin{axis}[
xlabel={$x$}, ylabel={$y$},
legend pos=north west,
grid=major,
]
\addplot[blue, thick, domain=0:6] {sin(deg(x))};
\addplot[red, thick, dashed, domain=0:6] {cos(deg(x))};
\legend{$\sin x$, $\cos x$}
\end{axis}Give each curve a different line style as well as a colour, so the chart still works printed in black and white.
Plotting your data from a CSV file
This is what most reports need: results exported from Python, Excel or a log, plotted as they are. Say training.csv holds:
epoch,train_loss,val_loss
1,0.92,0.95
2,0.61,0.70
3,0.44,0.58
4,0.35,0.55\begin{axis}[
xlabel={Epoch}, ylabel={Loss},
legend pos=north east,
]
\addplot[blue, thick, mark=*] table[x=epoch, y=train_loss, col sep=comma] {training.csv};
\addplot[red, thick, mark=square*] table[x=epoch, y=val_loss, col sep=comma] {training.csv};
\legend{Training, Validation}
\end{axis}Pick the columns by their header names. Upload the CSV next to your .tex file; when the numbers change, re-export it and recompile.
Thousands of points slow every compile. Thin them out with each nth point=10 in the plot options, or export fewer rows.
Points without a line
\addplot[only marks, mark=o] coordinates {
(0, 0.5) (1, 2.1) (2, 3.8) (3, 6.2) (4, 7.9)
};Bar charts
\begin{axis}[
ybar,
ylabel={Response time (ms)},
symbolic x coords={Login, Search, Export},
xtick=data,
nodes near coords,
ymin=0,
bar width=18pt,
legend style={at={(0.5,-0.18)}, anchor=north, legend columns=-1},
]
\addplot coordinates {(Login, 120) (Search, 85) (Export, 340)};
\addplot coordinates {(Login, 95) (Search, 60) (Export, 210)};
\legend{Before, After}
\end{axis}symbolic x coords lists the categories in order, xtick=data puts a tick under each one and nodes near coords prints the value on each bar. Two \addplot commands give grouped bars. Start bar charts at zero (ymin=0), or the differences look bigger than they are. Use xbar for horizontal bars when the labels are long.
Error bars
\addplot+[only marks, error bars/.cd, y dir=both, y explicit]
coordinates {
(1, 2.5) +- (0, 0.3)
(2, 3.1) +- (0, 0.4)
(3, 4.2) +- (0, 0.2)
};Logarithmic axes
Replace axis with semilogyaxis (log y), semilogxaxis (log x) or loglogaxis (both) when values span several orders of magnitude.
Size and style for the whole report
\pgfplotsset{
compat=1.18,
width=0.85\linewidth,
height=6cm,
grid=major,
grid style={gray!25},
tick label style={font=\small},
legend style={font=\small},
}Set these once in the preamble so every chart in the report has the same size and look. A single axis can still override them, for example [width=6cm] for two charts side by side.
3D surfaces
\begin{axis}[view={60}{30}, colormap/viridis]
\addplot3[surf, domain=-2:2, domain y=-2:2, samples=30] {exp(-x^2-y^2)};
\end{axis}In a figure
\begin{figure}[htbp]
\centering
\begin{tikzpicture}
\begin{axis}[...]
...
\end{axis}
\end{tikzpicture}
\caption{Training and validation loss}
\label{fig:loss}
\end{figure}Put the title in the caption, not on the chart with title=: the caption is numbered and appears in the list of figures.
Common options
| Option | Does |
|---|---|
xmin, xmax, ymin, ymax | Fixes the axis limits |
domain=a:b, samples=n | Range and resolution of a formula |
xlabel, ylabel | Axis labels; include the unit |
legend pos | north west, south east, outer north east, ... |
grid=major | Light grid lines at the major ticks |
mark=*, mark=square*, mark=o | Point markers |
width, height | Chart size |
each nth point=n | Plots one point in n, for large files |
Where to go next
- TikZ for diagrams, using the same drawing commands
- Tables, when exact values matter more than the trend
- Presenting your PFE to the jury