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:
- (Optional) Install the font in the system;
$ apt-get install msttcorefonts
- 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
- 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.scatter(np.random.rand(N), np.random.rand(N), s=area, c=np.random.rand(N), alpha=0.5) plt.title("Sample title") plt.ylabel("Random Value") plt.xlabel("Random Variable") plt.show()
Note: If the font is not rendered, it may be because matplotlib needs to refresh its font cache (see Kevin’s comment):
import matplotlib matplotlib.font_manager._rebuild()
2 Comments
One thing that may be needed: matplotlib.font_manager._rebuild() after you add the fonts. Your solution worked perfectly once I did that (found at http://bastibe.de/2016-05-30-matplotlib-font-cache.html). Thanks!
Thanks! I edited the post to mention this.