Mods to matplotlib to make it play nicely with LaTeX documents.
Nota bene: This package is deprecated; I use tueplots now :)
To install via pip on the command line, do:
python -m pip install git+https://github.com/eringrant/niceplotlibThe dependency can also be added to a requirements.txt or environment.yml file as:
niceplotlib @ git+https://github.com/eringrant/niceplotlibStart with importing the package in a Python script that produces matplotlib plots, which sets some text and color defaults:
import niceplotlib as nplThe package also includes utilities for sizing plots. See also "Saving plots" and "Including plots" for guidelines on the steps that follow.
First, determine text or column width of your target TeX document.
Add the statement \showthe\textwidth (\showthe\columnwidth for two-column format)
to your document:
\documentclass{report}
\begin{document}
...
\showthe\textwidth
...
\end{document}Then compile the document; the output will give something like:
> 345.0pt.
l.5 \showthe\textwidth345 is your document's width and is therefore the maximum width for an unscaled plot in your document.
Start with 345 as the width passed to npl.set_size, and adjust as needed.
Pass the target width determined
above to npl.set_size as the
figsize when creating a matplotlib plot. A minimal example is:
import niceplotlib as npl
import numpy as np
# Plot
x = np.linspace(0, 2*np.pi, 100)
fig, ax = plt.subplots(1, 1, figsize=npl.set_size(width))
ax.plot(x, np.sin(x))
ax.set_xlim(0, 2 * np.pi)
ax.set_xlabel(r'$\theta$')
ax.set_ylabel(r'$\sin (\theta)$')Plots should be saved in a vector format to prevent pixelation. Use either PDF:
fig.savefig('example.pdf', format='pdf', bbox_inches='tight')Or SVG, though you will have to do some extra work for conversion:
fig.savefig('example.svg', format='svg', bbox_inches='tight')Include the figure saved above into the TeX document using the graphicx package:
\begin{figure}
\centering
\includegraphics{example.pdf}
\end{figure}Ideally, the figure can be included just so without scaling in TeX! If the figure still isn't quite the right size, resize by tuning the target width in the instructions under "Sizing plots".
This package is heavily inspired by Jack Walton's post on "Plot publication-quality figures with matplotlib and LaTeX."