{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n.. redirect-from:: /tutorials/text/pgf\n\n\n# Text rendering with XeLaTeX/LuaLaTeX via the ``pgf`` backend\n\nUsing the ``pgf`` backend, Matplotlib can export figures as pgf drawing\ncommands that can be processed with pdflatex, xelatex or lualatex. XeLaTeX and\nLuaLaTeX have full Unicode support and can use any font that is installed in\nthe operating system, making use of advanced typographic features of OpenType,\nAAT and Graphite. Pgf pictures created by ``plt.savefig('figure.pgf')``\ncan be embedded as raw commands in LaTeX documents. Figures can also be\ndirectly compiled and saved to PDF with ``plt.savefig('figure.pdf')`` by\nswitching the backend ::\n\n matplotlib.use('pgf')\n\nor by explicitly requesting the use of the ``pgf`` backend ::\n\n plt.savefig('figure.pdf', backend='pgf')\n\nor by registering it for handling pdf output ::\n\n from matplotlib.backends.backend_pgf import FigureCanvasPgf\n matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)\n\nThe last method allows you to keep using regular interactive backends and to\nsave xelatex, lualatex or pdflatex compiled PDF files from the graphical user\ninterface. Note that, in that case, the interactive display will still use the\nstandard interactive backends (e.g., QtAgg), and in particular use latex to\ncompile relevant text snippets.\n\nMatplotlib's pgf support requires a recent LaTeX_ installation that includes\nthe TikZ/PGF packages (such as TeXLive_), preferably with XeLaTeX or LuaLaTeX\ninstalled. If either pdftocairo or ghostscript is present on your system,\nfigures can optionally be saved to PNG images as well. The executables\nfor all applications must be located on your :envvar:`PATH`.\n\n`.rcParams` that control the behavior of the pgf backend:\n\n================= =====================================================\nParameter Documentation\n================= =====================================================\npgf.preamble Lines to be included in the LaTeX preamble\npgf.rcfonts Setup fonts from rc params using the fontspec package\npgf.texsystem Either \"xelatex\" (default), \"lualatex\" or \"pdflatex\"\n================= =====================================================\n\n

Note

TeX defines a set of special characters, such as::\n\n # $ % & ~ _ ^ \\ { }\n\n Generally, these characters must be escaped correctly. For convenience,\n some characters (_, ^, %) are automatically escaped outside of math\n environments. Other characters are not escaped as they are commonly needed\n in actual TeX expressions. However, one can configure TeX to treat them as\n \"normal\" characters (known as \"catcode 12\" to TeX) via a custom preamble,\n such as::\n\n plt.rcParams[\"pgf.preamble\"] = (\n r\"\\AtBeginDocument{\\catcode`\\&=12\\catcode`\\#=12}\")

\n\n\n\n## Multi-Page PDF Files\n\nThe pgf backend also supports multipage pdf files using\n`~.backend_pgf.PdfPages`\n\n```python\nfrom matplotlib.backends.backend_pgf import PdfPages\nimport matplotlib.pyplot as plt\n\nwith PdfPages('multipage.pdf', metadata={'author': 'Me'}) as pdf:\n\n fig1, ax1 = plt.subplots()\n ax1.plot([1, 5, 3])\n pdf.savefig(fig1)\n\n fig2, ax2 = plt.subplots()\n ax2.plot([1, 5, 3])\n pdf.savefig(fig2)\n```\n.. redirect-from:: /gallery/userdemo/pgf_fonts\n\n## Font specification\n\nThe fonts used for obtaining the size of text elements or when compiling\nfigures to PDF are usually defined in the `.rcParams`. You can also use the\nLaTeX default Computer Modern fonts by clearing the lists for :rc:`font.serif`,\n:rc:`font.sans-serif` or :rc:`font.monospace`. Please note that the glyph\ncoverage of these fonts is very limited. If you want to keep the Computer\nModern font face but require extended Unicode support, consider installing the\n`Computer Modern Unicode`__ fonts *CMU Serif*, *CMU Sans Serif*, etc.\n\n__ https://sourceforge.net/projects/cm-unicode/\n\nWhen saving to ``.pgf``, the font configuration Matplotlib used for the\nlayout of the figure is included in the header of the text file.\n\n```python\nimport matplotlib.pyplot as plt\n\nplt.rcParams.update({\n \"font.family\": \"serif\",\n # Use LaTeX default serif font.\n \"font.serif\": [],\n # Use specific cursive fonts.\n \"font.cursive\": [\"Comic Neue\", \"Comic Sans MS\"],\n})\n\nfig, ax = plt.subplots(figsize=(4.5, 2.5))\n\nax.plot(range(5))\n\nax.text(0.5, 3., \"serif\")\nax.text(0.5, 2., \"monospace\", family=\"monospace\")\nax.text(2.5, 2., \"sans-serif\", family=\"DejaVu Sans\") # Use specific sans font.\nax.text(2.5, 1., \"comic\", family=\"cursive\")\nax.set_xlabel(\"\u00b5 is not $\\\\mu$\")\n```\n.. redirect-from:: /gallery/userdemo/pgf_preamble_sgskip\n\n\n## Custom preamble\n\nFull customization is possible by adding your own commands to the preamble.\nUse :rc:`pgf.preamble` if you want to configure the math fonts,\nusing ``unicode-math`` for example, or for loading additional packages. Also,\nif you want to do the font configuration yourself instead of using the fonts\nspecified in the rc parameters, make sure to disable :rc:`pgf.rcfonts`.\n\n```python\nimport matplotlib as mpl\n\nmpl.use(\"pgf\")\nimport matplotlib.pyplot as plt\n\nplt.rcParams.update({\n \"font.family\": \"serif\", # use serif/main font for text elements\n \"text.usetex\": True, # use inline math for ticks\n \"pgf.rcfonts\": False, # don't setup fonts from rc parameters\n \"pgf.preamble\": \"\\n\".join([\n r\"\\usepackage{url}\", # load additional packages\n r\"\\usepackage{unicode-math}\", # unicode math setup\n r\"\\setmainfont{DejaVu Serif}\", # serif font via preamble\n ])\n})\n\nfig, ax = plt.subplots(figsize=(4.5, 2.5))\n\nax.plot(range(5))\n\nax.set_xlabel(\"unicode text: \u044f, \u03c8, \u20ac, \u00fc\")\nax.set_ylabel(r\"\\url{https://matplotlib.org}\")\nax.legend([\"unicode math: $\u03bb=\u2211_i^\u221e \u03bc_i^2$\"])\n```\n.. redirect-from:: /gallery/userdemo/pgf_texsystem\n\n\n## Choosing the TeX system\n\nThe TeX system to be used by Matplotlib is chosen by :rc:`pgf.texsystem`.\nPossible values are ``'xelatex'`` (default), ``'lualatex'`` and ``'pdflatex'``.\nPlease note that when selecting pdflatex, the fonts and Unicode handling must\nbe configured in the preamble.\n\n```python\nimport matplotlib.pyplot as plt\n\nplt.rcParams.update({\n \"pgf.texsystem\": \"pdflatex\",\n \"pgf.preamble\": \"\\n\".join([\n r\"\\usepackage[utf8x]{inputenc}\",\n r\"\\usepackage[T1]{fontenc}\",\n r\"\\usepackage{cmbright}\",\n ]),\n})\n\nfig, ax = plt.subplots(figsize=(4.5, 2.5))\n\nax.plot(range(5))\n\nax.text(0.5, 3., \"serif\", family=\"serif\")\nax.text(0.5, 2., \"monospace\", family=\"monospace\")\nax.text(2.5, 2., \"sans-serif\", family=\"sans-serif\")\nax.set_xlabel(r\"\u00b5 is not $\\mu$\")\n```\n## Troubleshooting\n\n* On Windows, the :envvar:`PATH` environment variable may need to be modified\n to include the directories containing the latex, dvipng and ghostscript\n executables. See `environment-variables` and\n `setting-windows-environment-variables` for details.\n\n* Sometimes the font rendering in figures that are saved to png images is\n very bad. This happens when the pdftocairo tool is not available and\n ghostscript is used for the pdf to png conversion.\n\n* Make sure what you are trying to do is possible in a LaTeX document,\n that your LaTeX syntax is valid and that you are using raw strings\n if necessary to avoid unintended escape sequences.\n\n* :rc:`pgf.preamble` provides lots of flexibility, and lots of\n ways to cause problems. When experiencing problems, try to minimalize or\n disable the custom preamble.\n\n* Configuring an ``unicode-math`` environment can be a bit tricky. The\n TeXLive distribution for example provides a set of math fonts which are\n usually not installed system-wide. XeLaTeX, unlike LuaLaTeX, cannot find\n these fonts by their name, which is why you might have to specify\n ``\\setmathfont{xits-math.otf}`` instead of ``\\setmathfont{XITS Math}`` or\n alternatively make the fonts available to your OS. See this\n `tex.stackexchange.com question`__ for more details.\n\n __ https://tex.stackexchange.com/q/43642/\n\n* If the font configuration used by Matplotlib differs from the font setting\n in yout LaTeX document, the alignment of text elements in imported figures\n may be off. Check the header of your ``.pgf`` file if you are unsure about\n the fonts Matplotlib used for the layout.\n\n* Vector images and hence ``.pgf`` files can become bloated if there are a lot\n of objects in the graph. This can be the case for image processing or very\n big scatter graphs. In an extreme case this can cause TeX to run out of\n memory: \"TeX capacity exceeded, sorry\" You can configure latex to increase\n the amount of memory available to generate the ``.pdf`` image as discussed on\n [tex.stackexchange.com](https://tex.stackexchange.com/q/7953/).\n Another way would be to \"rasterize\" parts of the graph causing problems\n using either the ``rasterized=True`` keyword, or ``.set_rasterized(True)`` as\n per :doc:`this example `.\n\n* Various math fonts are compiled and rendered only if corresponding font\n packages are loaded. Specifically, when using ``\\mathbf{}`` on Greek letters,\n the default computer modern font may not contain them, in which case the\n letter is not rendered. In such scenarios, the ``lmodern`` package should be\n loaded.\n\n* If you still need help, please see `reporting-problems`\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }