How to use a (random) *.otf or *.ttf font in matplotlib?


How can I use any type of font in my font library on my computer (e.g. *otf or *ttf) in all my matplotlib figures?

9/16/2015 12:53:35 PM

Accepted Answer

See the example here:

In general, you'd do something like this if you're wanting to use a specific .ttf file. (Keep in mind that pointing to a specific font file is usually a bad idea!)

import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

prop = fm.FontProperties(fname='/usr/share/fonts/truetype/groovygh.ttf')
ax.set_title('This is some random font', fontproperties=prop, size=32)

enter image description here

Usually, you'd just point to the name of the font, and let matplotlib worry about finding the specific file. E.g.

import matplotlib.pyplot as plt

plt.title('This is some random font', family='GroovyGhosties', size=32)

If you want to have matplotlib always use a particular font, then customize your .matplotlibrc file. ( is what you'd want to set. Note that you should specify the name of the font, not the path to a specific .ttf file.)

As an example of doing this dynamically (i.e. without setting up a specific .matplotlibrc file):

import matplotlib as mpl
mpl.rcParams[''] = 'GroovyGhosties'

import matplotlib.pyplot as plt

plt.title('Everything is crazy!!!', size=32)

enter image description here

10/11/2011 3:44:44 PM

You can specify the font and override the default font family in matplot config as well, e.g. for *nix

~/.matplotlib/matplotlibrc sans-serif
font.sans-serif: your font,sans-serif

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow