Exporting Matplotlib Plots to LaTeX
This blog post explains how plots from matplotlib can be exported to PGF files, which in turn can be imported into $\LaTeX$ documents. All figures in this post are links that point to the source code used to generate them.
Motivation
Skip this part if you are already motivated, i.e. you know why you would want to export from matplotlib to LaTeX.
Suppose you have a Python script that produces a nice plot using matplotlib. You might save the plot with
plt.savefig('histogram.png', dpi=400)
and it will write a PNG file to the disk, which is ~141 KB in size (in the example).
However, importing this file as an image into a LaTeX document has some drawbacks. Most notably that
- the fonts of the document do not match the axes labels,
- the text is not searchable (“probability density” would not be found with
ctrl+f
), - the image gets blurry when the reader zooms in, and
- it is comparably large in file size.
The solution to all four problems is exporting a PGF file from matplotlib, so LaTeX itself can take care of rendering the figure.
Exporting Matplotlib Plots
Adjust your matplotlib script by adding the following lines after import matplotlib
:
matplotlib.use("pgf") matplotlib.rcParams.update({ "pgf.texsystem": "pdflatex", 'font.family': 'serif', 'text.usetex': True, 'pgf.rcfonts': False, })
Update the save command to write to .pgf
plt.savefig('histogram.pgf')
and make sure LaTeX is installed on the system. The command pdflatex
is needed. On Mac brew cask install mactex
does the job.
Running the script will output the histogram file in PGF format which can be imported with LaTeX.
Importing PGF with LaTeX
Place the PGF file in the LaTeX project folder and import it with the following code:
\begin{figure} \begin{center} \input{histogram.pgf} \end{center} \caption{A PGF histogram from \texttt{matplotlib}.} \end{figure}
The figure will appear in the document.

Adjusting the Plot Size
The PGF figure might be scaled undesirably, e.g. it can be too wide. In that case I found it helpful to determine the text width \textwidth
of the document with the command
\usepackage{layouts} [...] \printinunitsof{in}\prntlen{\textwidth}
and adjust the matplotlib figure based on that:
fig.set_size_inches(w=4.7747, h=3.5)
Scaling with matplotlib is better than scaling the entire PGF figure because the font sizes remain the same and match the text in the document.
References
- Blog post on the same topic by Sebastian Billaudelle
- TeX StackExchange Answer by blahdiblah: determining the text width in a document
- StackOverflow answer by Elenium: matplotlib rcParams configuration
- Matplotlib examples: histogram plot used in this post
Nice trick! I had to include package pgf in LaTeX, but apart from that it worked like a charm.
Good point, I should probably extend the post by that. Did you use
\usepackage{pgfplots}
?Yeah, pgfplots worked for me. I was getting “! LaTeX Error: File `pgfpicture.sty’ not found.” before I included it.
This instruction helped me a lot to export plots to my LaTeX report. Unfortunately, if I configure matplotlib to generate PGF files they are not shown in the report. If I disable matplotlib to generate PGF files they ara shown but PGF files are not generated. How can I have both?
That’s a very good question, I’m afraid I do not know the answer to it. If you happen to find a solution please share it here!
Thanks Timo! Windows users should install a tex distribution in order to compile
plt.savefig('*.pgf')
. MiKTeX worked for me.Thanks for pointing that out! Have a great day!
Note that this will not work for all plot types. For example, using
pcolormesh
(even withrasterize=True
) will result in aNotImplementedError
.How do I install Tex so that Python can access it on Mac OS? I am using Anaconda, and am having tremendous trouble in getting Latex installed on the system.
It should be independent of Anaconda. Maybe this answer on tex.stackexchange.com helps.
How could I align the pgf plot to the left in LaTex? It shows an indent and is not properly aligned
If you use Spyder, instead of
matplotlib.use("pgf")
use this:So you can visualizes your plots on the plot panel and still save them as
*.pgf
Thanks for sharing, Sandy!
Thank you very much for this post. Everything was working fine until I tried a log-scale. Does your histogram work if you add something like
ax.set_yscale('log')
?I am able to generate the .pgf file via matplotlib, but I am not able to include the image in my LaTeX document. I have included \usepackage{pgfplots}, yet I get the error – “! LaTeX Error: Unknown graphics extension: .pgf.” I am using Texmaker + MikTeX on Windows. Any idea how to solve this issue?
Thanks in advance!
I am not sure about the error; maybe this answer helps you.
Did you use
\includegraphics{test.pgf}
? If I’m using this command, I got the same error! LaTeX Error: Unknown graphics extension: .pgf.
. If I’m using\input{test.pgf}
everything is fine.Hi, I’ve just noticed, that hyperref with references on graphic doesn’t work properly. As you see in this screenshot for y-axis is the red square (active hyperlink) at the wrong position. Seems like some parameter is missed. But anyway it the best solution, that is possible to be found.
Thank you !!! Enjoy a nice day!
For the figure width, I use this
\def\svgwidth{\textwidth}\input{file.tex}
This works for Tex files generated with inkscape. They have the \svgwidth parameter inside that scales nicely. I will need to check the output from matplotlib to see if it has something similar. Thanks for the tip Timo
I had problems with the error:
Solved by switching to xelatex engine.
I appreciate you sharing it here! Thanks!
Thanks, this helped me.
Or better still, convert your matplotlib to LaTeX native TikZ with https://pypi.org/project/tikzplotlib/
Thank you for this post! Thanks to it I could implement some plots very good. Do you know how circuits from Qiskit can be implemented in latex with high quality? In Qiskit you have the option to get a Matplotlib output but when I try to implement this output in my latex document the alignment is not right.
For anyone wondering, I used this tutorial and received the error: RuntimeError: … not found. Install it or change rcParams[‘pgf.texsystem’] to an available TeX implementation.
What I had to do was close, and then re-open the project in my IDE (PyCharm), and then it worked.