Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท TikZ and Graphics

Charts and Plots with PGFPlots

Plot functions, data tables and CSV files in LaTeX with PGFPlots: axes, legends, bar charts, 3D surfaces, scientific styles and tips for consistent figures.

PGFPlots is a package built on TikZ for data visualisation. It draws axes with proper ticks, labels and legends, plots mathematical functions and tabulated data, and keeps the fonts and sizes of the figure aligned with your document. Because the plot is computed at compile time, the figure scales perfectly and can be changed by editing a number.

LATEX
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}   % use the current behaviour; adjust to your version

A first plot

LATEX
\begin{tikzpicture}
  \begin{axis}[
    xlabel={$x$}, ylabel={$f(x)$},
    domain=-3:3, samples=100,
    axis lines=left, grid=major,
    legend pos=north west,
  ]
    \addplot[blue, thick]  {x^2};
    \addplot[red, dashed]  {2*x + 1};
    \legend{$x^2$, $2x+1$}
  \end{axis}
\end{tikzpicture}

The expression inside braces uses the gnuplot-like syntax of pgfmath: x^2, sin(deg(x)) (note that trigonometric functions in pgfplots expect degrees unless you wrap with deg() or rad()), exp(-x), ln(x), sqrt(x).

Frequently used axis options:

  • Range: xmin, xmax, ymin, ymax, domain
  • Size: width=8cm, height=5cm
  • Scales: xmode=log, ymode=log for log axes
  • Ticks and labels: xtick={0,1,2,3}, xticklabels={a,b,c}, ytick distance=2
  • Style: axis lines=left, grid=both, title={...}, legend style={...}

The stand-in below samples a function the way PGFPlots does: it evaluates the function at samples points over the domain, and then connects them with straight lines.

JS Sampling a function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Plotting data

From inline coordinates:

LATEX
\addplot[mark=*, thick, blue] coordinates {
  (1, 2.1) (2, 3.9) (3, 6.2) (4, 8.1) (5, 9.8)
};

From a table:

LATEX
\addplot table [x=year, y=sales] {
  year sales
  2021 120
  2022 150
  2023 210
};

From a CSV file:

LATEX
\addplot table [col sep=comma, x=time, y=value] {measurements.csv};

Add +[only marks] for a scatter plot, error bars/.cd, y dir=both, y explicit with y error=err for error bars, and smooth for a Bezier-smoothed line. Use \addplot+[...] to keep the cycle list's colour and add options.

For styles that stay consistent across a paper, define a cycle list once:

LATEX
\pgfplotsset{
  every axis/.append style={font=\small, thick},
  cycle list={
    {blue, mark=*}, {red, mark=square*}, {green!50!black, mark=triangle*}, {orange, mark=diamond*}
  },
}

Bar charts

LATEX
\begin{tikzpicture}
  \begin{axis}[
    ybar, bar width=14pt,
    symbolic x coords={Python, Java, C, Go},
    xtick=data, ymin=0, ylabel={Score},
    nodes near coords,
    enlarge x limits=0.2,
  ]
    \addplot coordinates {(Python,82) (Java,74) (C,68) (Go,61)};
    \addplot coordinates {(Python,78) (Java,70) (C,72) (Go,55)};
    \legend{2024, 2025}
  \end{axis}
\end{tikzpicture}

ybar gives vertical bars and xbar horizontal ones; ybar stacked stacks series; ybar interval makes histograms of pre-binned data.

3D plots and contours

LATEX
\begin{tikzpicture}
  \begin{axis}[view={60}{30}, colormap/viridis, xlabel=$x$, ylabel=$y$, zlabel=$z$]
    \addplot3[surf, domain=-2:2, samples=25] {exp(-x^2 - y^2)};
  \end{axis}
\end{tikzpicture}

Use mesh, surf, contour gnuplot (needs gnuplot) or contour prepared. For heavy 3D plots, enable \usepgfplotslibrary{external} to avoid recompiling.

Layout in documents

  • Put each plot in a figure with a caption and label (labels).
  • Use width=\linewidth or width=0.48\textwidth for two plots side by side.
  • Use groupplots (library) for subplots sharing axes: \usepgfplotslibrary{groupplots}.
  • To get clean data, preprocess in Python or R and save a CSV; keep the figure code short.
  • Remove the need for gnuplot: PGFPlots can evaluate most functions itself; gnuplot is only needed for the more complex contour features.

Common errors

  • "Dimension too large": a function value is too big; set restrict y to domain=-100:100.
  • Using radians in sin: use sin(deg(x)).
  • Missing legend entries: add \addlegendentry{text} after each plot or \legend{...}.
  • Plot clipped: set clip=false or enlarge limits with enlargelimits.
  • Compatibility warning: add \pgfplotsset{compat=newest} or the version number.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which option sets the number of points PGFPlots computes for a function?

    samples controls how many points are evaluated over the domain; more samples give a smoother curve.
  2. 2. How do you plot values from measurements.csv?

    The table key reads a delimited file and x and y select the columns.
  3. 3. What unit do trigonometric functions in pgfplots expressions use by default?

    pgfmath uses degrees; wrap the argument in deg() when your x is in radians.
  4. 4. Which option draws vertical bars?

    ybar draws vertical bars, xbar draws horizontal ones.

Summary

  • PGFPlots draws axes and plots inside tikzpicture/axis with options for ranges, scales, grid and legend.
  • \addplot accepts expressions, coordinates, inline tables and CSV files.
  • ybar, xbar, stacked and interval modes make bar charts and histograms; addplot3 handles surfaces.
  • Define shared styles and cycle lists for consistency, and set compat.
  • Keep data preparation outside LaTeX when it gets heavy.

Next: Beamer Basics