Note

Go to the endto download the full example code.

Text rendering with XeLaTeX/LuaLaTeX via thepgf backend#

Using thepgf backend, Matplotlib can export figures as pgf drawingcommands that can be processed with pdflatex, xelatex or lualatex. XeLaTeX andLuaLaTeX have full Unicode support and can use any font that is installed inthe operating system, making use of advanced typographic features of OpenType,AAT and Graphite. Pgf pictures created byplt.savefig('figure.pgf')can be embedded as raw commands in LaTeX documents. Figures can also bedirectly compiled and saved to PDF withplt.savefig('figure.pdf') byswitching the backend

matplotlib.use('pgf')

or by explicitly requesting the use of thepgf backend

plt.savefig('figure.pdf',backend='pgf')

or by registering it for handling pdf output

frommatplotlib.backends.backend_pgfimportFigureCanvasPgfmatplotlib.backend_bases.register_backend('pdf',FigureCanvasPgf)

The last method allows you to keep using regular interactive backends and tosave xelatex, lualatex or pdflatex compiled PDF files from the graphical userinterface. Note that, in that case, the interactive display will still use thestandard interactive backends (e.g., QtAgg), and in particular use latex tocompile relevant text snippets.

Matplotlib's pgf support requires a recentLaTeX installation that includesthe TikZ/PGF packages (such asTeXLive), preferably with XeLaTeX or LuaLaTeXinstalled. If either pdftocairo or ghostscript is present on your system,figures can optionally be saved to PNG images as well. The executablesfor all applications must be located on yourPATH.

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"

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 mathenvironments. Other characters are not escaped as they are commonly neededin actual TeX expressions. However, one can configure TeX to treat them as"normal" characters (known as "catcode 12" to TeX) via a custom preamble,such as:

plt.rcParams["pgf.preamble"]=(r"\AtBeginDocument{\catcode`\&=12\catcode`\#=12}")

Multi-Page PDF Files#

The pgf backend also supports multipage pdf files usingPdfPages

frommatplotlib.backends.backend_pgfimportPdfPagesimportmatplotlib.pyplotaspltwithPdfPages('multipage.pdf',metadata={'author':'Me'})aspdf:fig1,ax1=plt.subplots()ax1.plot([1,5,3])pdf.savefig(fig1)fig2,ax2=plt.subplots()ax2.plot([1,5,3])pdf.savefig(fig2)

Font specification#

The fonts used for obtaining the size of text elements or when compilingfigures to PDF are usually defined in thercParams. You can also use theLaTeX default Computer Modern fonts by clearing the lists forrcParams["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']) orrcParams["font.monospace"] (default:['DejaVuSansMono','BitstreamVeraSansMono','ComputerModernTypewriter','AndaleMono','NimbusMonoL','CourierNew','Courier','Fixed','Terminal','monospace']). Please note that the glyphcoverage of these fonts is very limited. If you want to keep the ComputerModern font face but require extended Unicode support, consider installing theComputer Modern Unicode fontsCMU Serif,CMU Sans Serif, etc.

When saving to.pgf, the font configuration Matplotlib used for thelayout 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(figsize=(4.5,2.5))ax.plot(range(5))ax.text(0.5,3.,"serif")ax.text(0.5,2.,"monospace",family="monospace")ax.text(2.5,2.,"sans-serif",family="DejaVu Sans")# Use specific sans font.ax.text(2.5,1.,"comic",family="cursive")ax.set_xlabel("µ is not $\\mu$")

Custom preamble#

Full customization is possible by adding your own commands to the preamble.UsercParams["pgf.preamble"] (default:'') if you want to configure the math fonts,usingunicode-math for example, or for loading additional packages. Also,if you want to do the font configuration yourself instead of using the fontsspecified in the rc parameters, make sure to disablercParams["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 byrcParams["pgf.texsystem"] (default:'xelatex').Possible values are'xelatex' (default),'lualatex' and'pdflatex'.Please note that when selecting pdflatex, the fonts and Unicode handling mustbe 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 yourPATH (for raster output,pdftocairo or ghostscript is also required). ThePATH environmentvariable may need to be modified (in particular on Windows) to include thedirectories containing the executable. SeeEnvironment variables andSetting environment variables in Windows for details.

  • Sometimes the font rendering in figures that are saved to png images isvery bad. This happens when the pdftocairo tool is not available andghostscript 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 stringsif necessary to avoid unintended escape sequences.

  • rcParams["pgf.preamble"] (default:'') provides lots of flexibility, and lots ofways to cause problems. When experiencing problems, try to minimalize ordisable the custom preamble.

  • Configuring anunicode-math environment can be a bit tricky. TheTeXLive distribution for example provides a set of math fonts which areusually not installed system-wide. XeLaTeX, unlike LuaLaTeX, cannot findthese fonts by their name, which is why you might have to specify\setmathfont{xits-math.otf} instead of\setmathfont{XITSMath} oralternatively make the fonts available to your OS. See thistex.stackexchange.com question for more details.

  • If the font configuration used by Matplotlib differs from the font settingin yout LaTeX document, the alignment of text elements in imported figuresmay be off. Check the header of your.pgf file if you are unsure aboutthe fonts Matplotlib used for the layout.

  • Vector images and hence.pgf files can become bloated if there are a lotof objects in the graph. This can be the case for image processing or verybig scatter graphs. In an extreme case this can cause TeX to run out ofmemory: "TeX capacity exceeded, sorry" You can configure latex to increasethe amount of memory available to generate the.pdf image as discussed ontex.stackexchange.com.Another way would be to "rasterize" parts of the graph causing problemsusing either therasterized=True keyword, or.set_rasterized(True) asperthis example.

  • Various math fonts are compiled and rendered only if corresponding fontpackages are loaded. Specifically, when using\mathbf{} on Greek letters,the default computer modern font may not contain them, in which case theletter is not rendered. In such scenarios, thelmodern package should beloaded.

  • If you still need help, please seeGet help

Gallery generated by Sphinx-Gallery