Typevia
Graphics and Diagrams

Introduction to Pgfplots

While standard LaTeX can handle text and basic tables beautifully, creating high-quality, publication-ready graphs often requires external tools. Pgfplots is the solution to this problem. It is a powerful LaTeX package built on top of TikZ that allows you to create complex 2D and 3D plots directly within your .tex file.

The primary advantage of using Pgfplots over importing images from Excel or Python is consistency. Because the plots are rendered by LaTeX, the fonts, label sizes, and line weights perfectly match the rest of your document. Additionally, Pgfplots handles the scaling and axes automatically, ensuring your data is always represented accurately.

Getting Started: The Basic Structure

To use Pgfplots, you must include it in your preamble. You should also specify a "compatibility level" to ensure your document renders the same way even if the package is updated in the future.

\usepackage{pgfplots}
\pgfplotsset{compat=1.18} % Use the version installed on your system

Every graph follows a hierarchical structure:

  1. The tikzpicture environment: The general container for TikZ graphics.
  2. The axis environment: Defines the coordinate system, labels, and grid.
  3. The \addplot command: Defines the actual data or function to be drawn.

A Minimal Example

Here is the simplest possible graph:

\begin{tikzpicture}
\begin{axis}
    \addplot {x^2};
\end{axis}
\end{tikzpicture}

Note: Every \addplot command must end with a semicolon (;). Forgetting this is the most common cause of compilation errors in Pgfplots.

Plotting Mathematical Functions

Plotting a function like $f(x) = \sin(x)$ is straightforward. However, to make the plot look "smooth" and cover the right area, we use options inside square brackets.

Key Options:

  • domain: Specifies the range of x-values (e.g., domain=-2:2).
  • samples: Defines how many points Pgfplots calculates. The default is 25, which often looks "jagged." Increasing this to 100 or 200 creates a smooth curve.
  • color and style: You can change the line's appearance (e.g., blue, dashed, thick).

Example: A Smooth Trigonometric Function

In this example, we will plot two functions on the same axis.

\begin{tikzpicture}
\begin{axis}[
    xlabel={$x$},
    ylabel={$y$},
    title={Trigonometric Functions},
    grid=major,
]
    % First plot: a blue solid line
    \addplot[color=blue, samples=100, domain=0:2*pi] {sin(deg(x))};
    
    % Second plot: a red dashed line
    \addplot[color=red, dashed, samples=100, domain=0:2*pi] {cos(deg(x))};
    
    \legend{$\sin(x)$, $\cos(x)$}
\end{axis}
\end{tikzpicture}

Important: Pgfplots uses degrees for trigonometric functions by default. If your input $x$ is in radians, you must use the deg(x) function to convert it, as shown above.

Customizing the Axis Appearance

The axis environment accepts a wide range of options to improve readability and aesthetics. These options are placed in the [...] immediately following \begin{axis}.

Common Axis Customizations:

  • Labels: xlabel={Text}, ylabel={Text}
  • Limits: xmin=0, xmax=10 (forces the axis to start and end at specific values).
  • Grid lines: grid=major or grid=both.
  • Legend Position: legend pos=north west (or south east, outer north east, etc.).
  • Axis Lines: Use axis lines=middle to create a standard Cartesian "cross" layout rather than a box.

Example: A Customized Graph

\begin{tikzpicture}
\begin{axis}[
    axis lines = left,
    xlabel = {Time (s)},
    ylabel = {Velocity (m/s)},
    xmin=0, xmax=10,
    ymin=0, ymax=100,
    ytick={0,20,40,60,80,100},
    grid = minor,
    width=10cm, % Adjusts the width of the plot
    height=7cm  % Adjusts the height
]
\addplot [
    domain=0:10, 
    samples=100, 
    color=darkgray,
    very thick,
]
{x^2};
\addlegendentry{$v = t^2$}
\end{axis}
\end{tikzpicture}

Plotting Data Points and External Files

In many scientific scenarios, you aren't plotting a formula but rather experimental data. Pgfplots makes it easy to plot individual coordinates or import data from a .csv or .txt file.

Manual Coordinates

If you have a small number of points, you can provide them directly:

\begin{tikzpicture}
\begin{axis}
    \addplot[only marks, mark=square*] coordinates {
        (0,0) (1,2) (2,3) (3,5) (4,8)
    };
\end{axis}
\end{tikzpicture}

Importing from a Table

If you have a file named experiment_data.csv with columns named time and result, you can plot it like this:

\begin{tikzpicture}
\begin{axis}[xlabel=Time, ylabel=Result]
    \addplot table [x=time, y=result, col sep=comma] {experiment_data.csv};
\end{axis}
\end{tikzpicture}

Best Practice: Keep your data files in the same folder as your .tex file. Use col sep=comma for CSV files or col sep=space (the default) for standard text data.

Best Practices and Common Pitfalls

1. The "Memory Limit" Error

If you have a very large dataset (thousands of points), LaTeX might run out of memory.

  • Solution: Use the \usepgfplotslibrary{external} library. This "pre-renders" your graphs into separate PDF files, significantly speeding up compilation and saving memory.

2. Choosing the Right Samples

Don't set samples=1000 unless absolutely necessary. High sample rates make compilation slow. For most linear or slightly curved functions, samples=50 or 100 is plenty.

3. Using the smooth Option

If you have a limited number of data points but want a curved line between them, add the smooth option to your \addplot.

\addplot[smooth, blue] coordinates {(0,0) (1,2) (2,1) (3,4)};

4. Consistency in Versioning

Always include \pgfplotsset{compat=...}. If you don't, Pgfplots defaults to a very old version (1.3) to ensure backward compatibility, which might cause your labels to be positioned poorly or your legends to look strange.

Summary Checklist

  • Did you include \usepackage{pgfplots}?
  • Did you set the compat level?
  • Is your axis environment inside a tikzpicture?
  • Does every \addplot command end with a semicolon?
  • If using trigonometric functions, did you use deg(x)?

By mastering these basics, you can move away from low-resolution screenshots of graphs and start producing high-quality, professional visualizations directly within your LaTeX documents.