Text rendering with XeLaTeX/LuaLaTeX via the pgf backend
Using the pgf backend, Matplotlib can export figures as pgf drawing
commands that can be processed with pdflatex, xelatex or lualatex. XeLaTeX and
LuaLaTeX have full Unicode support and can use any font that is installed in
the operating system, making use of advanced typographic features of OpenType,
AAT and Graphite. Pgf pictures created by plt.savefig('figure.pgf')
can be embedded as raw commands in LaTeX documents. Figures can also be
directly compiled and saved to PDF with plt.savefig('figure.pdf') by
switching the backend
matplotlib.use('pgf')
or by explicitly requesting the use of the backend
The last method allows you to keep using regular interactive backends and to
save xelatex, lualatex or pdflatex compiled PDF files from the graphical user
interface. Note that, in that case, the interactive display will still use the
standard interactive backends (e.g., QtAgg), and in particular use latex to
compile relevant text snippets.
Matplotlib's pgf support requires a recent LaTeX installation that includes
the TikZ/PGF packages (such as TeXLive), preferably with XeLaTeX or LuaLaTeX
installed. If either pdftocairo or ghostscript is present on your system,
figures can optionally be saved to PNG images as well. The executables
for all applications must be located on your PATH.
rcParams that control the behavior of the pgf backend:
Parameter
Documentation
pgf.preamble
Lines to be included in the LaTeX preamble
pgf.rcfonts
Setup fonts from rc params using the fontspec package
pgf.texsystem
Either "xelatex" (default), "lualatex" or "pdflatex"
Multi-Page PDF Files
The pgf backend also supports multipage pdf files using
PdfPages
The fonts used for obtaining the size of text elements or when compiling
figures to PDF are usually defined in the rcParams. You can also use the
LaTeX default Computer Modern fonts by clearing the lists for rcParams["font.serif"] (default: ['DejaVuSerif','BitstreamVeraSerif','ComputerModernRoman','NewCenturySchoolbook','CenturySchoolbookL','Utopia','ITCBookman','Bookman','NimbusRomanNo9L','TimesNewRoman','Times','Palatino','Charter','serif']),
rcParams["font.sans-serif"] (default: ['DejaVuSans','BitstreamVeraSans','ComputerModernSansSerif','LucidaGrande','Verdana','Geneva','Lucid','Arial','Helvetica','AvantGarde','sans-serif']) or rcParams["font.monospace"] (default: ['DejaVuSansMono','BitstreamVeraSansMono','ComputerModernTypewriter','AndaleMono','NimbusMonoL','CourierNew','Courier','Fixed','Terminal','monospace']). Please note that the glyph
coverage of these fonts is very limited. If you want to keep the Computer
Modern font face but require extended Unicode support, consider installing the
Computer Modern Unicode fonts CMU Serif, CMU Sans Serif, etc.
When saving to .pgf, the font configuration Matplotlib used for the
layout of the figure is included in the header of the text file.
importmatplotlib.pyplotaspltplt.rcParams.update({"font.family":"serif",# Use LaTeX default serif font."font.serif":[],# Use specific cursive fonts."font.cursive":["Comic Neue","Comic Sans MS"],})fig,ax=plt.subplots(
Custom preamble
Full customization is possible by adding your own commands to the preamble.
Use rcParams["pgf.preamble"] (default: '') if you want to configure the math fonts,
using unicode-math for example, or for loading additional packages. Also,
if you want to do the font configuration yourself instead of using the fonts
specified in the rc parameters, make sure to disable rcParams["pgf.rcfonts"] (default: True).
importmatplotlibasmplmpl.use("pgf")importmatplotlib.pyplotaspltplt.rcParams.update({"font.family":"serif",# use serif/main font for text elements"text.usetex":True,# use inline math for ticks"pgf.rcfonts":False,# don't setup fonts from rc parameters"pgf.preamble":"\n".join([r"\usepackage{url}",# load additional packagesr"\usepackage{unicode-math}",# unicode math setupr"\setmainfont{DejaVu Serif}",# serif font via preamble])})fig,ax=plt.subplots(figsize=(4.5,2.5))ax.plot(range(5))ax.set_xlabel("unicode text: я, ψ, €, ü")ax.set_ylabel(r"\url{https://matplotlib.org}")ax.legend(["unicode math: $λ=∑_i^∞ μ_i^2$"])
Choosing the TeX system
The TeX system to be used by Matplotlib is chosen by rcParams["pgf.texsystem"] (default: 'xelatex').
Possible values are 'xelatex' (default), 'lualatex' and 'pdflatex'.
Please note that when selecting pdflatex, the fonts and Unicode handling must
be configured in the preamble.
importmatplotlib.pyplotaspltplt.rcParams.update({"pgf.texsystem":"pdflatex","pgf.preamble":"\n".join([r"\usepackage[utf8x]{inputenc}",r"\usepackage[T1]{fontenc}",r"\usepackage{cmbright}",]),})fig,ax=plt.subplots(figsize=(4.5,2.5))ax.plot(range(5))ax.text(0.5,3.,"serif",family="serif")ax.text(0.5,2.,"monospace",family="monospace")ax.text(2.5,2.,"sans-serif",family="sans-serif")ax.set_xlabel(r"µ is not $\mu$")
Troubleshooting
Make sure LaTeX is working and on your PATH (for raster output,
pdftocairo or ghostscript is also required). The PATH environment
variable may need to be modified (in particular on Windows) to include the
directories containing the executable. See Environment variables and
Setting environment variables in Windows for details.
Sometimes the font rendering in figures that are saved to png images is
very bad. This happens when the pdftocairo tool is not available and
ghostscript is used for the pdf to png conversion.
Make sure what you are trying to do is possible in a LaTeX document,
that your LaTeX syntax is valid and that you are using raw strings
if necessary to avoid unintended escape sequences.
rcParams["pgf.preamble"] (default: '') provides lots of flexibility, and lots of
ways to cause problems. When experiencing problems, try to minimalize or
disable the custom preamble.
Configuring an unicode-math environment can be a bit tricky. The
TeXLive distribution for example provides a set of math fonts which are
usually not installed system-wide. XeLaTeX, unlike LuaLaTeX, cannot find
these fonts by their name, which is why you might have to specify
\setmathfont{xits-math.otf} instead of \setmathfont{XITSMath} or
alternatively make the fonts available to your OS. See this
tex.stackexchange.com question for more details.
If the font configuration used by Matplotlib differs from the font setting
in yout LaTeX document, the alignment of text elements in imported figures
may be off. Check the header of your .pgf file if you are unsure about
the fonts Matplotlib used for the layout.
Vector images and hence .pgf files can become bloated if there are a lot
of objects in the graph. This can be the case for image processing or very
big scatter graphs. In an extreme case this can cause TeX to run out of
memory: "TeX capacity exceeded, sorry" You can configure latex to increase
the amount of memory available to generate the .pdf image as discussed on
tex.stackexchange.com.
Another way would be to "rasterize" parts of the graph causing problems
using either the rasterized=True keyword, or .set_rasterized(True) as
per this example.
Various math fonts are compiled and rendered only if corresponding font
packages are loaded. Specifically, when using \mathbf{} on Greek letters,
the default computer modern font may not contain them, in which case the
letter is not rendered. In such scenarios, the lmodern package should be
loaded.