Paalon
Paalon

Reputation: 83

How to use rc param `usetex=True` with other fonts in matplotlib

I want to plot with latex and other fonts but only latex font seems to be available. How can I enable other fonts with usetex?

import numpy as np
import matplotlib.pyplot as plt

plt.rc('text', usetex=True)
plt.rc('font', family='Arial')

plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.show()

Plotted image

Upvotes: 2

Views: 4623

Answers (1)

MaxNoe
MaxNoe

Reputation: 14997

Using usetex=True

You have to use your own LaTeX header for matplotlib. You can then use the fontpackages to select fonts.

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.unicode'] = True
plt.rcParams['text.latex.preamble'] = r'''
\usepackage{mathtools}

\usepackage{helvet}
\renewcommand{\familydefault}{\sfdefault}
% more packages here
'''

plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.savefig('test.pdf')

Result: usetex result

using the pgf backend

You get the most flexibility by using the pgf backend. This needs a recent LaTeX installation in the system.

For me, the most practical approach is to have a matplotlibrc and a header-matplotlib.tex and just include the texfile in the matplotlibrc. However, because matplotlib runs tex in a tmp directory, you need to add the current directory to the TEXINPUTS.

Example:

matplotlibrc

backend: pgf  # use the pgf backend
pgf.rcfonts : False # setup the fonts yourself in the header
text.usetex : True 
text.latex.unicode : True
pgf.texsystem : lualatex
pgf.preamble : \input{header-matplotlib.tex}

header-matplotlib.tex

\usepackage{fontspec}
\setsansfont{Arial}  # for the example I used Fira Sans

\usepackage{amssymb}
\usepackage{mathtools}

\usepackage{unicode-math}
\setmathfont{Latin Modern Math}

% more packages here

pgf_plot.py (This got much smaller, as we are setting the options in `matplotlibrc)

import matplotlib.pyplot as plt
import numpy as np

plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.savefig('test.pdf')

Run using

$ TEXINPUTS=$(pwd): python pgf_plots.py

Result:

Result

This approach can be extended, to match the fonts and font size of the plot to the ones used in your document, see the example here: https://github.com/Python4AstronomersAndParticlePhysicists/PythonWorkshop-ICE/tree/master/examples/use_system_latex

Upvotes: 5

Related Questions