How to Include a Matplotlib Figure in LaTeX
At a glance
- 1. Export the figure
Save the completed Matplotlib figure as a PDF for crisp vector output, or as PNG when you specifically need a raster image.
- 2. Place the files together
Put the exported file where LaTeX can find it, or provide a relative path to its folder.
- 3. Include it in LaTeX
Load graphicx and use includegraphics inside a figure environment, setting the width to fit your layout.
- 4. Check the result
Compile the document and inspect labels, fonts, and margins; adjust the figure size or export settings if needed.
If you mean Matplotlib’s pyplot interface, you usually do not need to redraw a complicated Python figure in PGFPlots. Export the finished figure from Python, then include the resulting file in your LaTeX document. For most plots, PDF is the best export format; it keeps lines and text sharp when scaled.
Export the figure from Matplotlib
Save the figure after you have added its plots, labels, legend, and other elements. For example:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 300)
fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
ax.plot(x, np.sin(x), label=r"$\sin(x)$")
ax.plot(x, np.cos(x), label=r"$\cos(x)$")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Two periodic functions")
ax.legend()
ax.grid(True, alpha=0.3)
fig.savefig("complex-figure.pdf", bbox_inches="tight")
plt.close(fig)
The script writes complex-figure.pdf to its current working directory. bbox_inches="tight" trims excess whitespace around the figure; if you need consistent margins or exact output dimensions, omit it and control the figure layout instead. The figsize values are in inches.
A PDF export is usually vector-based, which means plot lines and text remain crisp when enlarged. Images embedded inside the plot—such as photographs or rasterized collections—remain raster data. If you need a bitmap, save as PNG instead, for example fig.savefig("complex-figure.png", dpi=300, bbox_inches="tight"). The dpi setting affects raster output and raster elements, not the resolution of ordinary PDF vector paths.
Include the exported file in LaTeX
Keep the image in the same folder as your .tex file, or use a relative path to its location. This complete minimal document includes the PDF created by the Python example:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\begin{figure}[htbp]
\centering
\includegraphics[width=0.9\linewidth]{complex-figure.pdf}
\caption{Sine and cosine plotted with Matplotlib.}
\label{fig:complex-figure}
\end{figure}
Figure~\ref{fig:complex-figure} shows the two functions.
\end{document}
Compile with a LaTeX engine that accepts PDF graphics, such as pdflatex, LuaLaTeX, or XeLaTeX. Adjust 0.9\linewidth to change the displayed width while preserving the figure’s aspect ratio. If the file is in a subfolder named figures, write figures/complex-figure.pdf as the argument to \includegraphics.
Choosing PDF, PNG, or PGF
| Format | Use it when | Main trade-off |
|---|---|---|
| You want a scalable plot for a paper, report, or presentation | Usually the best default; some elements may be rasterized or use fonts differently from the document | |
| PNG | The image is inherently raster, or your workflow specifically requires a bitmap | Enlarging it can make edges and text look pixelated; choose an adequate resolution |
| PGF | You want plot text typeset by LaTeX to match the document’s fonts and math | Requires a compatible LaTeX setup and is less convenient than including a single PDF |
Matplotlib’s PGF backend can export a .pgf file that you include with \input{complex-figure.pgf}. Set up the backend before importing pyplot, and test the exported file with the same LaTeX engine and packages as your document. This can give consistent LaTeX typography, but a complicated figure may produce a larger or slower-to-compile document. For many uses, a PDF is simpler and more reliable.
Common mistakes
- Using the wrong file name or path: LaTeX must be able to find the exported file from the directory where the document is compiled. Check capitalization and the extension; file names can be case-sensitive.
- Expecting
\includegraphicsto run Python: It only inserts an existing image file. Run the Python script first, or use a separate automated build workflow that generates the figure before LaTeX compilation. - Exporting a low-resolution bitmap: A PNG can look blurry when enlarged. Increase its
dpior use PDF when the figure consists mainly of lines, markers, and text. - Forcing an unsuitable size: Scaling a whole figure too small also shrinks its labels. Increase the Matplotlib figure size or font sizes, or allocate more width in the LaTeX document.
- Assuming
pgfplotsis required: PGFPlots is useful when you want to construct the plot in LaTeX, but it is not required to include a plot created in Python. Use\includegraphicsfor the straightforward export-and-include workflow.
References
Spotted an error? Send a correction. Read how we write and check articles in our editorial policy.