# 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 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 $$...$$) 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