Plot a function in LaTeX (pgfplots)

Load pgfplots, open an axis environment inside a tikzpicture and write \addplot[domain=-2:2] {x^2};. pgfplots computes the points, scales the axes and labels them.

Preamble

The snippets on this page need these lines before \begin{document}:

\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

Plot one function

The expression in braces is a function of x. Write every multiplication with *, as in 2*x; powers use ^, and sqrt, exp, ln and abs are available. domain is the range of x, and samples the number of computed points. The defaults are -5:5 and 25 points.

\begin{tikzpicture}
\begin{axis}[xlabel={$x$}, ylabel={$f(x)$}]
\addplot[blue, domain=-2:2, samples=50] {x^2 - 2*x};
\end{axis}
\end{tikzpicture}
Result
The compiled example

Open in the editor

Plot several functions with a legend

Each \addplot adds a curve, and the \addlegendentry after it names the curve in the legend. Options of axis apply to all curves: grid=major draws grid lines at the tick marks, legend pos moves the legend, and width and height set the size of the plot.

\begin{tikzpicture}
\begin{axis}[
  xlabel={$x$}, ylabel={$y$},
  domain=0:4, samples=50,
  grid=major, legend pos=north west,
  width=9cm, height=6cm
]
\addplot[blue] {x^2};
\addlegendentry{$x^2$}
\addplot[red, dashed] {exp(x/2)};
\addlegendentry{$e^{x/2}$}
\end{axis}
\end{tikzpicture}
Result
The compiled example

Open in the editor

Plot sine and cosine

sin, cos and tan expect degrees. For x in radians, set trig format plots=rad in the axis options or write sin(deg(x)).

\begin{tikzpicture}
\begin{axis}[
  trig format plots=rad,
  domain=-2*pi:2*pi, samples=100,
  xlabel={$x$}, legend pos=south west
]
\addplot[blue] {sin(x)};
\addlegendentry{$\sin x$}
\addplot[red] {cos(x)};
\addlegendentry{$\cos x$}
\end{axis}
\end{tikzpicture}
Result
The compiled example

Open in the editor

Put the axes through the origin and limit the range

axis lines=middle replaces the box by two axes through the origin. ymin and ymax set the visible range. For a function with a pole, restrict y to domain=-10:10 drops the points outside that range, so pgfplots draws no line across the pole.

\begin{tikzpicture}
\begin{axis}[
  axis lines=middle,
  xlabel={$x$}, ylabel={$y$},
  ymin=-5, ymax=5,
  restrict y to domain=-10:10
]
\addplot[blue, domain=-3:3, samples=200] {1/x};
\end{axis}
\end{tikzpicture}
Result
The compiled example

Open in the editor

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages