matplotlib Integration with TeX/LaTeX Inserting TeX formulae in plots


Example

TeX formulae can be inserted in the plot using the rc function

import matplotlib.pyplot as plt
plt.rc(usetex = True)

or accessing the rcParams:

import matplotlib.pyplot as plt
params = {'tex.usetex': True}
plt.rcParams.update(params)

TeX uses the backslash \ for commands and symbols, which can conflict with special characters in Python strings. In order to use literal backslashes in a Python string, they must either be escaped or incorporated in a raw string:

plt.xlabel('\\alpha')
plt.xlabel(r'\alpha')

The following plot Plot showing TeX in labels and legend can be produced by the code

import matplotlib.pyplot as plt
plt.rc(usetex = True)
x = range(0,10)
y = [t**2 for t in x]
z = [t**2+1 for t in x]
plt.plot(x, y, label = r'$\beta=\alpha^2$')
plt.plot(x, z, label = r'$\beta=\alpha^2+1$')
plt.xlabel(r'$\alpha$')
plt.ylabel(r'$\beta$')
plt.legend(loc=0)
plt.show()

Displayed equations (such as $$...$$ or \begin{equation}...\end{equation}) are not supported. Nevertheless, displayed math style is possible with \displaystyle.

To load latex packages use the tex.latex.preamble argument:

params = {'text.latex.preamble' : [r'\usepackage{siunitx}', r'\usepackage{amsmath}']}
plt.rcParams.update(params)

Note, however, the warning in the example matplotlibrc file:

#text.latex.preamble : # IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES
                       # AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT ASK FOR HELP
                       # IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO.
                       # preamble is a comma separated list of LaTeX statements
                       # that are included in the LaTeX document preamble.
                       # An example:
                       # text.latex.preamble : \usepackage{bm},\usepackage{euler}
                       # The following packages are always loaded with usetex, so
                       # beware of package collisions: color, geometry, graphicx,
                       # type1cm, textcomp. Adobe Postscript (PSSNFS) font packages
                       # may also be loaded, depending on your font settings