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}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}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}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}Pitfalls
- Without
\pgfplotsset{compat=1.18}(or the version you have), pgfplots prints a warning and uses the defaults of an old version. - A function that grows far beyond
yminandymaxcan stop with Dimension too large.restrict y to domainremoves those points before they are drawn. - More samples give a smoother curve and a longer compile time. 50 to 200 points are enough for most curves.
Compiled with pdfLaTeX from TeX Live 2023.
Related pages
- Package
pgfplots - Package
tikz - How-to Plot data from a file in LaTeX
- How-to Create a bar chart in LaTeX
- Error Dimension too large