How to Create Publication-Ready Plots with LaTeX | by Aruna Pisharody | Towards Data Science

If you’ve ever written an article in a scientific journal, chances are that you’ve used a LaTeX template for preparing your manuscript. It is after all the industry standard in typesetting documents. However, how many of you have considered LaTeX as a plotting tool?
LaTeX offers a powerful visualization library, PGFPlots, based on its graphics system, PGF/TikZ. This makes it effortless to include plots directly within your .tex document. It has a simple user-interface that even amateur programmers can comfortably master. However, there is a staggering variety of other plotting options available to us online; be it popular data science programming languages such as Python and R, who boast of their own impressive data visualization libraries, or plotting software such as Origin, Veusz, GraphRobot, and Orange. Most such options also afford the flexibility to work with very large datasets and execute complex mathematical computations, which, unfortunately, the PGFPlots library does not. However, if these drawbacks do not pose an issue for you, the PGFPlots library will assuredly render you the highest quality plots compared to most other options available today.
However, although not as steep as other languages/tools, plotting with LaTeX also comes with its own learning curve. PGFPlots does provide its own comprehensive manual, but you need to know what to search for to find your answers in there! And, often times, we are looking for abstract ideas rather than a complete picture. And this is where sites like tex.stackexchange.com comes to the rescue. Even so, I still had to dig through tons of stackexchange posts and suffer through numerous trial-and-error before I struck gold. Ergo my decision to write this article. I hope to introduce you to the basics of plotting in LaTeX by working through 5 types of fundamental plots one may encounter in a scientific publication. Each plot will be focused on different types of customization available in the PGFPlots library. You will need only a basic familiarity with LaTeX to understand this article. Of course, this is just to kick off your journey into plotting with LaTeX. I hope to dive into more complex plots in future articles, so consider this as setting the scene for a series of articles.
So without further ado, let’s get started!
Let’s begin by setting the document preamble for plotting in LaTeX. As with any .tex file, we’ll begin by defining our document type using the \documentclass command. We’ll also add the recommended encoding package for our document. Since we are plotting using PGFPlots, we’ll be calling the PGFPlots package. The \pgfplotsset command in the next line is used to define a particular set of options for the entire document (or, as we’ll see later, a part of the document). In this case, we are setting the compatibility option for the entire document to be PGFPlots 1.9 to ensure backward compatibility. Note: it is a good practice to always include this line in your preamble to avoid changes in your output due to version updates.
\documentclass[12pt, a4paper]{article}\usepackage[utf8]{inputenc}\usepackage{pgfplots}\pgfplotsset{compat=1.9}
Next, let us set some common style specifications for our plots using the \pgfplotsset command (named myplotstyle). Note: if needed, we can always override these styles within a particular axis environment.
\pgfplotsset{    myplotstyle/.style={    legend style={draw=none, font=\small},    legend cell align=left,    legend pos=north east,    ylabel style={align=center, font=\bfseries\boldmath},    xlabel style={align=center, font=\bfseries\boldmath},    x tick label style={font=\bfseries\boldmath},    y tick label style={font=\bfseries\boldmath},    scaled ticks=false,    every axis plot/.append style={thick},    },}
A brief description of the styling options mentioned above:
legend style , legend cell align , and legend pos : used for legend styling; in this case, sets a legend without border, \small font, left-aligned text, and positioned to the north-east of the plotxlabel style and ylabel style : used to change x-axis and y-axis label styles; here, they are used to bold the axes labels (\bfseries for text and \boldmath for numerical axes labels) and align them to the center of the axesx tick label style and y tick label style : used to set axes tick label styles; here, the tick font is set to be bold for both text and numerical tick labelsevery axis plot./append style : used to set styles for every axis within a plot; here, thickness of lines and markers in the plot is set to be thick . Note: here, I have used every axis plot option to change the line widths for the plots onlyscaled y ticks=false : used to prevent PGFPlots from factoring out common exponents for axes tick labels
legend style , legend cell align , and legend pos : used for legend styling; in this case, sets a legend without border, \small font, left-aligned text, and positioned to the north-east of the plot
xlabel style and ylabel style : used to change x-axis and y-axis label styles; here, they are used to bold the axes labels (\bfseries for text and \boldmath for numerical axes labels) and align them to the center of the axes
x tick label style and y tick label style : used to set axes tick label styles; here, the tick font is set to be bold for both text and numerical tick labels
every axis plot./append style : used to set styles for every axis within a plot; here, thickness of lines and markers in the plot is set to be thick . Note: here, I have used every axis plot option to change the line widths for the plots only
scaled y ticks=false : used to prevent PGFPlots from factoring out common exponents for axes tick labels
Now, let us define a simple plotting environment styled using myplotstyle to check how it looks! The code for this purpose is given below:
\begin{tikzpicture}\begin{axis}[    myplotstyle,]\end{axis}\end{tikzpicture}
Since PGFPlots is based on PGF/TikZ, each plot should be placed within a picture environment given by \begin{tikzpicture} ... \end{tikzpicture}. Within this, we will define a normal axis environment and set our preferred stylings for it. On the right hand side, we can see how our simple axes plot looks like! Note: I have added a comma after my last styling option, myplotstyle . Although this is not a requirement, it is a good practice to follow. This way you can mitigate any potential errors that may surface when introducing additional styling options at a later point in time.
Next, let’s move on and check out how to use datasets for creating plots. For larger datasets, it would be prudent to save the .csv files externally. However, in the case of smaller datasets, as I have used in the present article, you can always define them locally within the .tex file outside the \begin{document} ... \end{document} tags. This can be done using the following code:
\begin{filecontents*}{filename.csv}...\end{filecontents*}
In either case, we can use the same method described in the following section to add data for plotting.
Looks like we’re all set to move forward with plotting now. Let’s get plotting!
The first plot that we’ll be creating is a simple line plot (in our case, with markers). The dataset I’ll be using for this purpose is shown below. Note: for brevity, I’m only using the first four months for my explanation; I have, however, also added a figure for how our plot will look like when including the entire dataset.
Now, let’s start plotting our dataset. The format for plotting columns from a dataset is as shown below:
\addplot+[<options>] table[x=colname,y=colname, col sep=sep] {filename.csv};
It is required to add a ; after each \addplot command. Note: you can also use \addplot[<options>] instead of \addplot+[<options] . The difference between the two is only in whether you wish to append your <options> to the default cycle list (options controlling line styles) or ignore the cycle list completely. For details regarding the different cycle list available in PGFPlots, you may refer to Chapter 4, Section 4.7.7 in the PGFPlots manual.
Let’s just combine all that we learnt till now to create a simple line plot using our dataset. The code so far is shown below:
\begin{tikzpicture}\begin{axis}[    myplotstyle,]\addplot+[] table[x=year,y=Jan, col sep=comma] {Fig_lineplot.csv};\addplot+[] table[x=year,y=Feb, col sep=comma] {Fig_lineplot.csv};\addplot+[] table[x=year,y=Mar, col sep=comma] {Fig_lineplot.csv};\addplot+[] table[x=year,y=Apr, col sep=comma] {Fig_lineplot.csv};\end{axis}\end{tikzpicture}
As we can see from the figure on the left hand side, significant work is still required to make this plot appealing.
Let’s tackle the x-axis and y-axis labels first! Adding the axes labels is very straightforward. Simply add xlabel={Year} and ylabel={No. of passengers} within the axis options. Another obvious styling is adding the legend keys. This can be done by adding legend entries={Jan, Feb, Mar, Apr} . Also, myplotstlye positions the legend to the north-east of our plot. As can be observed from our plot, that would block the plot content in this case. Therefore, let’s move our legend for this plot to the south-east using legend pos=south east . Other options available for legend pos are south west, north east, and north west . You can also add the legend keys outside the plot by using the option outer north east.
There is a glaring mistake in the plotted figure; each x-tick label is a year, but is displayed with a comma separator. This can be fixed by changing the number format of the x-tick label as:
x tick label style={/pgf/number format/.cd,                     set thousands separator={}}
I would also like the x-tick label to be rotated by 90 degrees, so I’ll also add rotate=90 to the x-tick label styling. The final axis options are as follows:
\begin{axis}[    myplotstyle,    legend pos=south east,    legend entries={Jan, Feb, Mar, Apr},    xlabel={Year},    ylabel={No. of passengers},    x tick label style={rotate=90,     /pgf/number format/.cd, set thousands separator={}},   ]}
Let’s start styling our lines and markers now. These style options are to be included within the \addplot+[<options>] . Let’s add the following options for lines/markers:
smooth : interpolates between two points to make the transition smooth
smooth : interpolates between two points to make the transition smooth
2. mark= : you can either specify your preferred marker style (an extensive list of marks option is provided in the PGFPlots manual) or use the default line styles in the cycle list . Adding a * at the end (say, triangle*) signifies that the marker needs to be filled with the corresponding line color
3. mark options={} : here, you can specify marker size , whether you wish to scale the marker size, fill it with a specific color, etc.
A sample \addplot command with options will look like this:
\addplot+[smooth, mark=diamond*, mark options={scale=2,fill=white}] table[x=year,y=Jan, col sep=comma] {Fig_lineplot.csv};
And it’s as simple as that! The final code put together will look like this:
\begin{tikzpicture}\begin{axis}[    myplotstyle,    legend pos=south east,    legend entries={Jan, Feb, Mar, Apr},    xlabel={Year},    ylabel={No. of passengers},    x tick label style={rotate=90, /pgf/number format/.cd, set thousands separator={}},]\addplot+[smooth, mark=diamond*, mark options={scale=2,fill=white}] table[x=year,y=Jan, col sep=comma] {Fig_lineplot.csv};\addplot+[smooth, mark=*, mark options={scale=1.5,fill=white}] table[x=year,y=Feb, col sep=comma] {Fig_lineplot.csv};\addplot+[smooth,, mark=triangle*, mark options={scale=2,fill=white}] table[x=year,y=Mar, col sep=comma] {Fig_lineplot.csv};\addplot+[smooth, mark=square*, mark options={scale=1.5,fill=white}] table[x=year,y=Apr, col sep=comma] {Fig_lineplot.csv};\end{axis}\end{tikzpicture}
And this is the final plot outcome:
A sample plot using the entire dataset is also shown below:
The next plot we’re going to generate is a simple logarithmic plot. We’ll use this plot to explore two customizations:
How to plot a log-log or semi-log plot using PGFPlots?How to use column data from .csv files as axis tick labels?
How to plot a log-log or semi-log plot using PGFPlots?
How to use column data from .csv files as axis tick labels?
The dataset used for this plot is shown below. As we can see from the dataset, it has two columns: month and corresponding number of confirmed COVID-19 cases in the state of Maharashtra in India for the year 2020. Only one of these columns needs to be plotted; the other column is to be used as the x-axis tick labels. So how do we go about plotting this using PGFPlots?
Let’s first create a simple plot based on what we have learnt so far:
\begin{tikzpicture}\begin{axis}[    myplotstyle,    xlabel={Month $(2020)$},    ylabel={No. of confirmed cases},]\addplot+[mark=o,mark options={scale=1.5}] table[x expr=\coordindex, y=confirmed, col sep=comma] {Fig_semilogplot.csv};\end{axis}\end{tikzpicture}
Here, since we do not have any column to be plotted on the x-axis, we use x expr=\coordindex to plot the y-axis data against coordinate index. The plot that we get is shown on the left hand side. It is difficult to correctly infer the pandemic behavior from this plot. In such cases, it is more prudent to rearrange this information on a log-log axis (in our case, a semi-log axis). In order to change our plot from normal to semi-log, we’ll need to modify the axis environment from begin{axis} ... \end{axis} to \begin{semilogyaxis} ... \end{semilogyaxis} (since we want to change only our y-axis to logarithmic scale). Other options for logarithmic axis environments include semilogxaxis and loglogaxis . As can be seen from this figure, we can infer the trend with greater clarity using the semi-log feature in our plot.
However, there are still many issues with the plot. Taking a look at the x-axis tick labels, we can see that no information can be gained from the default ticks provided by x expr=\coordindex . To use the month column values in the .csv file as x-axis tick labels, we will add the following axis options:
table/col sep=comma,xticklabels from table={filename.csv}{colname}
First, we need to specify the column separator for our .csv file using the table/col sep option. Then, we can direct PGFPlots to retrieve the x-tick labels from a particular column in the table using the command xticklabels from table .
Another styling preference is how to display the logarithmic axis tick labels. Some prefer to display it using scientific notation, while others would like the numbers to be displayed as is. If you wish to display the logarithmic axis tick labels as a fixed number, then you can use the command log ticks with fixed point to display all logarithmic axes with fixed number notations. Since a semi-log plot has only a single logarithmic axis, this is quite straightforward to use. However, if you’re plotting a log-log figure and wish to modify only a single logarithmic axis to fixed number notations, then this post on stackexchange can help!
We’re almost done with our styling! Let’s rotate the x-tick labels by 90 degrees using the command that we learnt before. Also, we’ll use xtick option to specify tick positions for our plot. The possible values for the xtick option are \empty , data , or {<list of coordinates>}. \empty will produce no tick marks and {<list of coordinates>} will produce tick marks at the provided coordinates. Since we are specifying our x-axis tick labels from .csv file, we will use xtick=data to produce tick marks at every coordinate of our plot. And one final modification before we are done; since we’re using discrete data points for plotting, we will remove the line joining the markers. For this purpose, PGFPlots provides us with the only marks option that can be added to the \addplot command. Note: in contrast, if you wish to show only lines without markers, you can use the no marks option.
And that’s it! Our final code for the semi-log plot will look like this:
\begin{tikzpicture}\begin{semilogyaxis}[    myplotstyle,    table/col sep=comma,    xticklabels from table={Fig_loglog_lineplot.csv}{month},    xtick=data,    x tick label style={rotate=90},    xlabel={Month $(2020)$},    ylabel={No. of confirmed cases},    log ticks with fixed point,]\addplot+[only marks, mark=o, mark options={scale=1.5}] table[x expr=\coordindex, y=confirmed, col sep=comma] {Fig_loglog_lineplot.csv};\end{semilogyaxis}\end{tikzpicture}
Here, we can see how our corresponding plot looks like:
Moving on to our next plot now! Let’s take a look at how to plot a secondary y-axis. For ease of plotting, I have modified the tips dataset provided by seaborn (Python plotting library) into two separate .csv files (tip amount during lunch hour and tip amount during dinner hour). Note: you can also use multiple columns within a single .csv file to plot the same.
We’ll begin by writing down the specifications for the two axes environments that we’re interested in.
\begin{tikzpicture}%% axis 1 %%\begin{axis}[    myplotstyle,    scale only axis,    axis y line*=left,    xlabel={Total bill $(\$)$},    ylabel={Tips $(\$)$},]\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\end{axis}%% axis 2 %%\begin{axis}[    myplotstyle,    scale only axis,    axis y line*=right,    axis x line=none,    ylabel={Tips $(\$)$},]\addplot+[only marks, mark=triangle*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\end{axis}\end{tikzpicture}
Now, we’ll layer the two environments over each other. For this, we will use the \pgfplotsset{set layers} option right after \begin{tikzpicture}. Some additional styling options also need to be specified:
axis y line*=left/right : specifies which dataset is shown on which y-axis. Note: the * signifies that axes will not have arrow headsaxis x line=none : hides x-axis line for the second plotscale only axis : forces both y-axes dimensions to be the same
axis y line*=left/right : specifies which dataset is shown on which y-axis. Note: the * signifies that axes will not have arrow heads
axis x line=none : hides x-axis line for the second plot
scale only axis : forces both y-axes dimensions to be the same
The combined code now looks like this:
\begin{tikzpicture}\pgfplotsset{set layers}%% axis 1 %%\begin{axis}[    myplotstyle,    scale only axis,     axis y line*=left,    xlabel={Total bill $(\$)$},    ylabel={Tips $(\$)$},]\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\end{axis}%% axis 2 %%\begin{axis}[    myplotstyle,    scale only axis,    axis y line*=right,    axis x line=none,    ylabel={Tips $(\$)$},]\addplot+[only marks, mark=triangle*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\end{axis}\end{tikzpicture}
The initial plot based on these specifications is shown below:
What styling options can we add to make this plot more appealing? Let’s start by making both the y-axes limits to be the same. This can be done adding ymin and ymax for both axes. Let us also change the color of the left ordinate to blue and right to red. We do this by setting the options y axis line style , y tick label style , and ylabel style for both axes. We’ll also match the marker color to their corresponding axis color.
The code thus far is:
\begin{tikzpicture}\pgfplotsset{set layers}%% axis 1 %%\begin{axis}[    myplotstyle,    scale only axis,    axis y line*=left,    ymin=0, ymax=7,    y axis line style={blue},    y tick label style={blue},    ylabel style={blue},    xlabel={Total bill $(\$)$},    ylabel={Tips $(\$)$},]\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\end{axis}%% axis 2%%\begin{axis}[    myplotstyle,    scale only axis,    axis y line*=right,    ymin=0, ymax=7,    axis x line=none,    y axis line style={red},    tick label style={red},    ylabel style={red},    ylabel={Tips $(\$)$},]\addplot+[only marks, mark=triangle*, color=red, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\end{axis}\end{tikzpicture}
This is how our plot looks like now:
Since our y-axes labels are the same, it would be prudent to also add a legend to make this plot more informative. We’ll need some tweaking to render a single legend for both axes environments. I used the workaround proposed on stackexchange for this purpose. We’ll add a label to the first plot and use this label to create a legend entry for the first plot inside the second axis environment. The final code put together will look like this:
\begin{tikzpicture}\pgfplotsset{set layers}\begin{axis}[    myplotstyle,    scale only axis,    axis y line*=left,    ymin=0, ymax=7,    y axis line style={blue},    y tick label style={blue},    ylabel style={blue},    xlabel={Total bill $(\$)$},    ylabel={Tips $(\$)$},]\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\label{multiplot:plot1}\end{axis}\begin{axis}[    myplotstyle,    scale only axis,    axis y line*=right,    ymin=0, ymax=7,    axis x line=none,    y axis line style={red},    y tick label style={red},    ylabel style={red},    ylabel={Tips $(\$)$},    legend pos=south east,]\addlegendimage{/pgfplots/refstyle=multiplot:plot1}\addlegendentry{Tips during lunch hour}\addplot+[only marks, mark=triangle*, color=red, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\addlegendentry{Tips during dinner hour}\end{axis}\end{tikzpicture}
As we can see from the code above, another way to add a legend entry is using the \addlegendentry[<options>]{text} after the \addplot command. I have used \addlegendimage{} command with it for referencing the line style of the first plot. We will then add the legend for the plot in this axis environment after its corresponding \addplot command. Note: I have added the legend of the first plot before the \addplot command in the second plot to preserve order.
And there we have it! This is our final plot:
The next scenario we’re going to tackle is how to add text within plots. For this, let’s once again use the tips dataset (both lunch and dinner hour datasets combined) to create a mean plot.
As always, let’s begin by using what we have learnt so far to create a basic plot:
\begin{tikzpicture}\begin{axis}[    myplotstyle,    xlabel={Total bill ($\$$)},    ylabel={Tips ($\$$)},]\addplot+[only marks, mark=square, color=red, mark options={scale=2}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\addplot+[only marks, mark=square, color=red, mark options={scale=2}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\end{axis}\end{tikzpicture}
This is what we’re starting off with:
Now, we need to add a mean line and two standard deviation lines (mean + 2σ and mean-2σ; I have calculated the necessary values beforehand). To plot constant values, we can either use the format \addplot+[]{constant} (in which case, we’ll have to specify the domain in which the line needs to be plotted) or \addplot+[] coordinates{(x,y)} . Note: I have used both the options for reference. I have also specified the domain for constant value plots. Since adding a domain can cause changes in the axis limits, I have added xmin , xmax, xtick, and ytick . This is our code so far:
\begin{tikzpicture}\begin{axis}[    myplotstyle,    xlabel={Total bill ($\$$)},    ylabel={Tips ($\$$)},    xmin=0, xmax=40,    xtick={5,10,15,20,25,30,35},    ytick={1,2,3,4,5,6},    domain=5:35,]\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\addplot+[smooth, no marks, color=black, dashdotted] {2.97};\addplot+[smooth, no marks, color=black, solid] {0.62};\addplot+[smooth, no marks, color=black, solid] coordinates {(5, 5.32) (35, 5.32)};\end{axis}\end{tikzpicture}
And the corresponding plot output is:
The plot is incomplete until we add in the descriptions for each of the constant lines. The method I’m going to use here is to add a node at desired locations. I’ll be positioning my text based on rel axis cs (or, relative axis coordinate system; see figure below for details).
The format followed for adding a node is:
\node[<options>] at (rel axis cs: x,y) {text};
The final code after adding in the text descriptions will look this:
\begin{tikzpicture}\begin{axis}[    myplotstyle,    xlabel={Total bill ($\$$)},    ylabel={Tips ($\$$)},    xmin=0, xmax=40,    xtick={5,10,15,20,25,30,35},    ytick={1,2,3,4,5,6},    domain=5:35,]\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\addplot+[smooth, no marks, color=black, dashdotted] {2.97};\node [] at (rel axis cs: 0.2,0.51) {Mean};\addplot+[smooth, no marks, color=black, solid] coordinates {(5, 5.32) (35, 5.32)};\node [] at (rel axis cs: 0.24,0.87) {Mean + $2\sigma$};\addplot+[smooth, no marks, color=black, solid] {0.62};\node [] at (rel axis cs: 0.23,0.13) {Mean - $2\sigma$};\end{axis}\end{tikzpicture}
And we have our final plot as shown below:
Now, the last plot I’ll be tackling in this article is a plot overlaid on an image. I’ll be using the image shown below for this purpose. Note: I’ll be removing the axes and tick labels provided in the chart below and instead adding in my own axes and tick labels.
I’ll be using a fictitious weights dataset for this plot (see below).
Let’s first create a simple plot based on our dataset. The code so far with the corresponding plot is given below:
\begin{tikzpicture}\begin{axis}[    myplotstyle,    legend pos=south east,    legend entries={{\large Child 1}, {\large Child 2}},    xlabel={Age (in years)},    ylabel={Weight (in $kg$)},]\addplot+[only marks, mark options={scale=1.5}, mark=triangle,color=blue] table[x=age,y=weight1, col sep=comma] {Fig_overlaidplot.csv};\addplot+[only marks, mark options={scale=1.5}, mark=square,color=red] table[x=age,y=weight2, col sep=comma] {Fig_overlaidplot.csv};\end{axis}\end{tikzpicture}
We’ll modify few things to have matching dimensions and axes tick labels for both our plot and the image:
We’ll add width and height options to change dimension of our plotWe’ll use xmin, xmax , ymin , and ymax options to align our axis limits with the imageFinally, we’ll add xtick and ytick options to match our plot axes tick labels with those of the image (I have specified the weight for y-axis only in the metric unit)
We’ll add width and height options to change dimension of our plot
We’ll use xmin, xmax , ymin , and ymax options to align our axis limits with the image
Finally, we’ll add xtick and ytick options to match our plot axes tick labels with those of the image (I have specified the weight for y-axis only in the metric unit)
Our code put together will look like this:
\begin{tikzpicture}\begin{axis}[    myplotstyle,    legend pos=south east,    legend entries={{\large Child 1}, {\large Child 2}},    xlabel={Age (in years)},    ylabel={Weight (in $kg$)},    ymin=5, ymax=105,    ytick={10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100},    xmin=2, xmax=21,    xtick={2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20},    width=13cm, height=15cm,]\addplot+[only marks, mark options={scale=1.5}, mark=triangle,color=blue] table[x=age,y=weight1, col sep=comma] {Fig_overlaidplot.csv};\addplot+[only marks, mark options={scale=1.5}, mark=square,color=red] table[x=age,y=weight2, col sep=comma] {Fig_overlaidplot.csv};\end{axis}\end{tikzpicture}
And the corresponding plot for this will be:
Now, the command to add in graphics to the plot is:
\addplot graphics[<options>] {figure.png};
The central idea behind this plot is to fit the graphics within our plot axes coordinates. Therefore, we’ll have to add the \addplot graphics command with options xmin , xmax , ymin , and ymax matching those of the main plot. I have also added the axis on top option to have the axis lines and ticks positioned over the image.
And it’s as simple as that! The final code will be:
\begin{tikzpicture}\begin{axis}[    myplotstyle,    legend pos=south east, legend entries={{\large Child 1}, {\large Child 2}},    xlabel={Age (in years)},    ylabel={Weight (in $kg$)},    ymin=5, ymax=105,    ytick={10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100},    xmin=2, xmax=21,    xtick={2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20},    axis on top,    width=13cm, height=15cm,]\addplot+[only marks, mark options={scale=1.5}, mark=triangle,color=blue] table[x=age,y=weight1, col sep=comma] {Fig_overlaidplot.csv};\addplot+[only marks, mark options={scale=1.5}, mark=square,color=red] table[x=age,y=weight2, col sep=comma] {Fig_overlaidplot.csv};\addplot graphics[ymin=5, ymax=105, xmin=2, xmax=21] {Fig_comparisons.png};\end{axis}\end{tikzpicture}
And our overlaid plot will look like this:
And that’s a wrap... for this article!
Of course, this is just a sliver of the whole scope that LaTeX presents to us! Plotting with LaTeX might look daunting to a beginner. My hope is that this article will help a newbie from getting overwhelmed by the wealth of information available to them and encourage them to use this amazing tool. I will even consider this article a success if it has persuaded you to at least give plotting with LaTeX a try!