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 either switching to the backend
matplotlib.use('pgf')
or registering it for handling pdf output
from matplotlib.backends.backend_pgf import FigureCanvasPgf
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)
The second method allows you to keep using regular interactive backends and to save xelatex, lualatex or pdflatex compiled PDF files from the graphical user interface.
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.
Rc parameters 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”
Note
TeX defines a set of special characters, such as:
# $ % & ~ _ ^ \ { }
Generally, these characters must be escaped correctly. For convenience, some characters (_,^,%) are automatically escaped outside of math environments.
The fonts used for obtaining the size of text elements or when compiling figures to PDF are usually defined in the matplotlib rc parameters. You can also use the LaTeX default Computer Modern fonts by clearing the lists for font.serif, font.sans-serif or font.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.
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.use("pgf")
pgf_with_rc_fonts = {
"font.family": "serif",
"font.serif": [], # use latex default serif font
"font.sans-serif": ["DejaVu Sans"], # use a specific sans-serif font
}
mpl.rcParams.update(pgf_with_rc_fonts)
import matplotlib.pyplot as plt
plt.figure(figsize=(4.5,2.5))
plt.plot(range(5))
plt.text(0.5, 3., "serif")
plt.text(0.5, 2., "monospace", family="monospace")
plt.text(2.5, 2., "sans-serif", family="sans-serif")
plt.text(2.5, 1., "comic sans", family="Comic Sans MS")
plt.xlabel(u"µ is not $\\mu$")
plt.tight_layout(.5)
Full customization is possible by adding your own commands to the preamble. Use the pgf.preamble parameter 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 pgf.rcfonts.
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.use("pgf")
pgf_with_custom_preamble = {
"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": [
r"\usepackage{units}", # load additional packages
r"\usepackage{metalogo}",
r"\usepackage{unicode-math}", # unicode math setup
r"\setmathfont{xits-math.otf}",
r"\setmainfont{DejaVu Serif}", # serif font via preamble
]
}
mpl.rcParams.update(pgf_with_custom_preamble)
import matplotlib.pyplot as plt
plt.figure(figsize=(4.5,2.5))
plt.plot(range(5))
plt.xlabel(u"unicode text: я, ψ, €, ü, \\unitfrac[10]{°}{µm}")
plt.ylabel(u"\\XeLaTeX")
plt.legend([u"unicode math: $λ=∑_i^∞ μ_i^2$"])
plt.tight_layout(.5)
The TeX system to be used by matplotlib is chosen by the pgf.texsystem parameter. 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.
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.use("pgf")
pgf_with_pdflatex = {
"pgf.texsystem": "pdflatex",
"pgf.preamble": [
r"\usepackage[utf8x]{inputenc}",
r"\usepackage[T1]{fontenc}",
r"\usepackage{cmbright}",
]
}
mpl.rcParams.update(pgf_with_pdflatex)
import matplotlib.pyplot as plt
plt.figure(figsize=(4.5,2.5))
plt.plot(range(5))
plt.text(0.5, 3., "serif", family="serif")
plt.text(0.5, 2., "monospace", family="monospace")
plt.text(2.5, 2., "sans-serif", family="sans-serif")
plt.xlabel(u"µ is not $\\mu$")
plt.tight_layout(.5)