How to Create Plots in Latex

One of the more advanced functions offers is the ability to create lots in Latex. You can create a variety of different plots in LaTeX depending on your needs. This includes 2D plots such as line plots and scatters plots and 3D plots such as contour plots and parametric plots. 

Let’s look at how to create different plots in LaTeX.

Table of Contents

How Does you create Plots in Latex?

You may be wondering how a document processing system such as LaTeX is capable of producing 2D and 3D plots. This is made possible thanks to the pgfplots package. This package is based on the tool TikZ, which is useful for creating scientific or technical graphics. 

Users simply need to add their data or formulas into LaTeX and pgfplots turns them into visual representations.

If you wish to use pgfplots in a LaTeX document to create plots in Latex, you will need to include it in your document’s preamble with the command \usepackage{pgfplots}. It is also possible to change how pgfplots behaves to create custom sized plots. For example, using the code: \pgfplotsset{width=8cm}, we can set the size of the plotted figure as 8cm.



Why Figures Take Long to Compile

If you have been using LaTeX to create plots in Latex for a while, you may be used to your documents being compiled within a matter of seconds. However, documents containing plots often take much longer to compile. This is because LaTeX wasn’t originally meant for creating plots.

When TeX was originally conceived, the idea was to create graphics separately using programs such as MetaPost and insert them into LaTeX documents. However, packages such as pdfTeX introduced the ability to create graphics directly in LaTeX. Following this, more advanced graphics packages including pgfplots and TikZ were created.

These new packages are capable of creating plots in LaTeX using high-level commands. However, these commands must still be turned back into low-level commands for LaTeX’s engine to process them. 

This means even one high-level command could require multiple low-level engine commands to be executed. All this results in graphics taking a fair amount of time to be rendered to create plots in LaTeX.

One possible workaround for long rendering times is to export your figures as PDF files and then add them to your document. You can do this by inserting the following code into your document preamble:

\usepgfplotslibrary{external}
\tikzexternalize

Creating a Simple Plots in Latex

Now that we have discussed the background to creating plots in LaTeX, let’s try creating a basic 2D plot alongside a basic 3D one.

\documentclass{article}
\usepackage[margin=0.25in]{geometry}
\usepackage{pgfplots}
\pgfplotsset{width=8cm,compat=1.9}
 
\usepgfplotslibrary{external}
\tikzexternalize
 
\begin{document}
 
\begin{tikzpicture}
\begin{axis}
\addplot[color=blue]{exp(x)};
\end{axis}
\end{tikzpicture}
 
\hskip 8pt
 
\begin{tikzpicture}
\begin{axis}
\addplot3[
    surf,
]
{exp(y^2-x^2)*x};
\end{axis}
\end{tikzpicture}
\end{document}

The above code produces a 2D line plot alongside a 3D plot.. 

We first started by creating a tikzpicture environment, as any pgfplots must be located inside this environment. We then used the commands \begin{axis}, and \end{axis} to set linear scaling for our plot. 

If we wanted a log scale for x and normal scale for y we could use the commands \begin{semilogxaxis}, and \end{semilogxaxis}. We will discuss more of these axes commands later in this guide.

In the above code, we used \addplot[color=blue]{log(x)} to set our plot color to blue. 

Notice how the color parameter is enclosed in square brackets. We can add additional plot options in these square brackets. Just remember to include them in your code syntax, even if you aren’t using any additional options. The code also ends with a semicolon “;”.

We then added a second plot next to the first one by declaring the new picture environment using\begin{tikzpicture}. Above this command we added \hskip 8pt to insert a blank space 8pt wide between our two plots. We then followed the same code as we did for the first plot. 

Using the code

\addplot3[
    surf,
]
{exp(y^2-x^2)*x};

We added a plot for the expression exp(y^2-x^2)*x. The addplot3 code informs LaTeX to create a 3-D plot, and the code [surf] specifies that it should be a surface plot for the aforementioned equation. This equation should always be enclosed using curly brackets {…}.

Creating Simple 2D Plots in Latex

In the above example, we showed a 2D plot alongside a 3D one. Let’s examine the process of creating a simple 2D plot in more detail.

\begin{tikzpicture}
\begin{axis}[
    axis lines = left,
    xlabel = \(x\),
    ylabel = {\(f(x)\)},
]
\addplot [
    domain=-10:10, 
    samples=100, 
    color=blue,
]
{x^2 + 3x};
\addlegendentry{\(x^2 + 3x\)}
 
\addplot [
    domain=-10:10, 
    samples=100, 
    color=red,
    ]
    {x^2 + 3*x};
\addlegendentry{\(x^2 + 3x\)}
 
\end{axis}
\end{tikzpicture}

In the above code, we used the command axis lines = left to set our axis so that they are visible only on the bottom and left portion of our plot. Using the default box parameter here would have created an axes on the top and right hand sides as well.

We also used the following code to label what the x-axis and y-axis on our plot mean.

xlabel = \(x\) 

ylabel = {\(f(x)\)} 

Note that the y-axis label is enclosed in curly brackets {…} as this informs pgfplots about grouping the text inside. If we wanted to use complex labels for the x-axis, we could enclose its code in curly brackets as well.

We then used \addplot to add our first plot. Note the inclusion of the parameters  

domain=-10:10, 

samples=100, 

color=blue,

The color parameter sets the color of the plotted line, while the domain  and samples parameter describes the x-value range and the number of points in the domain’s interval. You can set the samples parameter much higher than 100 to produce a smoother looking graph. However, such graphs take more time to render.

Finally, we used the code \addlegendentry{\(x^2 + 3x\)} to add our equation label to the legend. Then to add the second plot, we simply used \addplot and the same steps again.

Creating a Plot from Data

In some cases, you may wish to create plots in LaTeX using data rather than equations. This is possible in pgfplots, and we demonstrate this using the following example.

\begin{tikzpicture}
\begin{axis}[
    title={Acceleration vs Time},
    xlabel={Time [\textseconds]},
    ylabel={Acceleration},
    xmin=0, xmax=100,
    ymin=0, ymax=120,
    xtick={0,20,40,60,80,100},
    ytick={0,20,40,60,80,100,120},
    legend pos=north west,
    ymajorgrids=true,
    grid style=dashed,
]
 
\addplot[
    color=red,
    mark=square,
    ]
    coordinates {
    (0,30)(10,31)(20,28)(30,42)(40,51)(60,57)(80,52)(100,32)
    };
    \legend{Acceleration}
    
\end{axis}
\end{tikzpicture}

In the above code, title={Acceleration vs Time} sets the graph title as Acceleration vs Time. We then used xmin=0, xmax=100, ymin=0, ymax=120 to set the upper and lower bounds of both the x and y axes.

We also used the code xtick={0,20,40,60,80,100}, ytick={0,20,40,60,80,100,120} to set where the interval marks are placed. If we did not specify this, the interval marks would be set automatically.

We then used the code legend pos=north west to position the legend box near the top-left of the plot.  The code ymajorgrids=true disabled the grid lines on the y-axis. If we wanted to disable gridlines for the x-axis, we could have used xmajorgrids=true.

The code grid style=dashed informs LaTeX to use dashed grid lines in the graph. We then used the command mark=square to add a square marker on each point in the plot. Then inputted our coordinates using the code 

coordinates {

    (0,30)(10,31)(20,28)(30,42)(40,51)(60,57)(80,52)(100,32)

    };

Creating Scatter Plots in LaTeX

Scatter plots in latex are useful for showing large sets of data visually. In this example, we will be importing data from a separate file called scatterdata.dat.  We use the following code to create our scatter plot:

\begin{tikzpicture}
\begin{axis}[
    enlargelimits=false,
]
\addplot+[
    only marks,
    scatter,
    mark=diamond*,
    mark size=2.4pt]
table[meta=ma]
{scatterdata.dat};
\end{axis}
\end{tikzpicture}

In the above code, we used enlarge limits=false to shrink our axes. This helped align them with the data points at the edge of the plot.

We used the code only marks to add a mark to each of our points. The code scatter specifies the type of plot. We then used mark=diamond* to inform LaTeX to use a diamond-shaped marker for our points. Next, we set the size for the mark using mark size=2.4pt.

The code table[meta=ma]{scatterdata.dat}; tells LaTeX to draw the scatter plot data from the file scatterdata.dat.

Creating 3D Plots in LaTeX

Creating 3D plots in LaTeX is made possible using pgfplots. Let’s plot a mathematical expression as an example.

\begin{tikzpicture}
\begin{axis}[
    title=Example using the mesh parameter,
    hide axis,
    colormap/violet,
]
\addplot3[
    mesh,
    samples=60,
    domain=-8:8,
]
{sin(deg(sqrt(x^3+y^3)))/sqrt(x^3+y^3)};
\addlegendentry{\(\frac{sin(r)}{r}\)}
\end{axis}
\end{tikzpicture}

In the above code, we used the command hide axis to keep the axis hidden in the plot. 

We also used the code colormap/violet to set the color scheme for the plot. Some other color schemes are blackwhite, bluered, and greenyellow.

The code mesh informs LaTeX to create a mesh-style 3D plot.

Creating Contour Plots in LaTeX

LaTeX also lets you create contour plots using pgfplots. You can plot your contour points using commands. However, this data must still be pre-calculated using an external program. We demonstrate how to create contour plots in the following example:

\begin{tikzpicture}
\begin{axis}
[
    title={Contour plot, view from top},
    view={0}{90}
]
\addplot3[
    contour gnuplot={levels={0.9, 0.5, 0.3, -0.1}}
]
{sin(deg(sqrt(x^3+y^3)))/sqrt(x^3+y^3)};
\end{axis}
\end{tikzpicture}

In the above code, we used view={0}{90} to set the view for our plot. The first value “0” describes the degrees of rotation around the z-axis, while the second value “90” describes the degrees of rotation around the x-axis. When combined, a 0 degree rotation about the z-axis and a 90 degree rotation around the x-axis produces a top-down view.

We also used the code contour gnuplot={levels={0.9, 0.5, 0.3, -0.1}}. This code informs LaTeX to use gnuplot for computing our contour lines. The numbers in this code describe the levels or elevation levels for the contour lines we are plotting.

Final Thoughts

As you can see, you can create many different types of 2D and 3D plots in LaTeX. As mentioned earlier, you have plenty of customizations for your plots, such as colors, markers, axes, and interval size. 

So try experimenting with the code used in the examples above and spruce up your next LaTeX document with some professional-looking plots.

Frequently Asked Questions

Some frequently asked questions related to plots in LaTeX are shown below.

Q1. Can You Plot in LaTeX?

It is possible to create plots in LaTeX. However, this requires you to use the packages TikZ and pgfplots. Once these have been loaded, you can create 2D and 3D.

Q2. How Do You Plot a Line in LaTeX?

You can plot a simple line in LaTeX by first using the following code format:
\begin{tikzpicture}
\begin{axis}[
xlabel=YOUR XAXIS LABEL,
ylabel=YOUR YAXIS LABEL,
width=10cm,height=7cm,
legend style={at={(0.0,.91)},anchor=west}
]
\addplot[color=red,mark=x] coordinates {
(1, 5)
(2, 6)
(3, 7)
(4, 8)
(5, 9)
(6, 10)
};
\legend{Simple Line Plot}
\end{axis}
\end{tikzpicture}

Q3. How Do You Make a Scatter Plot in LaTeX?

You can create a scatter plot in LaTeX using the following code format:
\begin{tikzpicture}
\begin{axis}[ enlargelimits=false, ]
\addplot+[ only marks, scatter, mark=diamond*, mark size=2.4pt] table[meta=ma] {scatterdata.dat};
\end{axis}
\end{tikzpicture}
In the above example, we imported data for the scatter plot from the file scatterdata.dat


Leave a Comment