Custom LaTeX fonts in matplotlib - tiagopereira/python_tips GitHub Wiki

One of matplotlib's advantages is the ability to use LaTeX to render fonts and expressions, allowing a greater integration and flexibility when including figures in LaTeX documents. Matplotlib's documentation already provides a very good overview on how to change LaTeX fonts, but it is limited to a few fonts, and the tick mark numbers will always appear as roman font. How to add a new font, including in the tick marks?

First, different fonts in LaTeX have different ways to be used. The simplest are included with a \usepackage{font} command, but others may vary. Check here for a list of LaTeX fonts. The easiest way to include different fonts in matplotlib is to control the text.latex.preamble option. This is not supported by matplotlib, and might cause problems. Before anything else, I suggest deleting the .matplotlib/tex.cache directory. This will avoid a lot of headaches later on. Then, issue the following commands:

rc('text.latex',preamble=r'\usepackage{myfont}')
rc('text',usetex=True)

This will change the roman font to myfont. Unless you pass the labels/text as r'\rm{aaaa}', the font shown by matplotlib will still be the default sans serif font. Some fonts will have support for math fonts. For those only, you can use the math option in usepackage:

rc('text.latex',preamble=r'\usepackage[math]{myfont}')

This will make the tick mark numbers to be also in myfont, instead of the default math font (roman).