Fonts and Matplotlib

There are a few posts on StackOverflow about changing the font used by matplotlib, but I was not able to find a practical solution, particularly if the font is not part of the current set of system fonts.

To use a new font:

  1. (Optional) Install the font in the system;
$ apt-get install msttcorefonts
  1. Copy the font to matplotlib font directory. In this case, it’s in a virtualenv (server);
$ cp usr/share/fonts/truetype/msttcorefonts/Times_New_Roman* ~/.virtualenvs/server/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf
  1. Clear the font cache;
$ rm ~/.cache/matplotlib/fontList.cache

The font should be available for plotting. Testing with the scatter example from matplotlib’s documentation:

import numpy as np
import matplotlib.pyplot as plt

plt.rc('font',family='Times New Roman')

N = 50
area = np.pi * (15 * np.random.rand(N))**2 
plt.title("Sample title")
plt.ylabel("Random Value")
plt.xlabel("Random Variable")

Changing the font of a matplotlib plot

Note: If the font is not rendered, it may be because matplotlib needs to refresh its font cache (see Kevin’s comment):

import matplotlib


Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>