The pgfplots package
Draws function plots, data plots and bar charts with axes, ticks and a legend: \addplot inside an axis environment.
Loading the package
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}pgfplots builds on tikz and loads it. You give a formula or a table of values; the package computes the axis range, the tick marks and the scaling. The plot is drawn in the document itself, so its labels use the document fonts.
An axis environment inside a tikzpicture is one coordinate system. Each \addplot adds a curve: from an expression in braces, from coordinates {...}, or from a file with table {...}. Like every TikZ path, \addplot ends with a semicolon.
\pgfplotsset{compat=1.18} selects the behaviour of that version. Set it in every document, so a later version of the package does not change your plots.
Main commands
\begin{axis}[xlabel={$x$}, ylabel={$y$}] ... \end{axis} | A coordinate system with axis labels. |
\addplot[domain=0:4, samples=50] {x^2}; | Plots a function of x between 0 and 4, computed at 50 points. |
\addplot coordinates {(0,1) (1,3) (2,2)}; | Plots points given in the source. |
\addplot table[x=x, y=y, col sep=comma] {data.csv}; | Plots two columns of a CSV file, selected by their header names. |
\addlegendentry{measured} | Legend text for the plot before it. |
\begin{axis}[ybar, symbolic x coords={A,B,C}, xtick=data] | Bar chart with named categories on the x axis. |
grid=major, legend pos=north west | Axis options: grid lines at the main ticks and the position of the legend. |
Complete example
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xlabel={$x$}, ylabel={$y$},
grid=major, legend pos=north west
]
\addplot[blue, thick, domain=0:4, samples=50] {x^2};
\addlegendentry{$x^2$}
\addplot[red, only marks, mark=*] table[x=x, y=y, col sep=comma] {data.csv};
\addlegendentry{measured}
\end{axis}
\end{tikzpicture}
\end{document}File data.csv:
x,y
0,0.2
1,0.9
2,4.3
3,8.8
4,16.5Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
- Without
\pgfplotsset{compat=...}the log warns that the package is "running in backwards compatibility mode". A value above the installed version is an error; TeX Live 2023 accepts at most1.18. - Trigonometric functions expect degrees. For a variable in radians write
sin(deg(x)). - An
\addplotwithout the semicolon stops the run with File ended while scanning use of \@xdblarg.
Related pages
- How-to Plot a function in LaTeX
- How-to Plot data from a file in LaTeX
- How-to Create a bar chart in LaTeX
- Package
tikz