8

I'm trying to use a TTF font in matplotlib; the .ttf file is downloaded and lives locally on my machine. I've followed other instructions on this site for selecting the font using font_manager; however, any text that I generate trying to use the font properties still appears in the default matplotlib font.

I know that Python does successfully find the font file, since prop.get_name() and similar commands do show the attributes of the font I want - but that's not what appears on my figure. Any suggestions?

As an example:

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

fig, ax = plt.subplots()

prop = fm.FontProperties(fname='/Users/smith/fonts/coolfont.ttf')
ax.set_title('Text in a cool font', fontproperties=prop, size=40)

fig.show()
Community
  • 1
  • 1
kwill
  • 81
  • 1
  • 4
  • 1
    try clearing your font cache in the mpl directory (e.g., ~/.matplotlib) – Paul H Oct 09 '12 at 17:56
  • I deleted the font cache file in the mpl directory. Running the code again did not change the results. I'll note that it's not just using a specific *.ttf font - even for fonts in my mpl-data/fonts/ directory, setting a different family name in `Font Manager` never changes what appears in the plot window. – kwill Oct 16 '12 at 16:51
  • hmmm. Only other thing I can think of is to change your 4th line to: `prop = fm.FontProperties(fname='coolfont')` – Paul H Oct 16 '12 at 17:04
  • 1
    Tried that as well with no luck. Still puzzled. – kwill Oct 25 '12 at 01:59
  • I was having the same problem. I eventually realized that I had a line in my matplotlibrc that specified text.usetex = True that I had forgotten to set to False. – jdmcbr Mar 02 '13 at 07:46

1 Answers1

6

its because of the backend that you are using.

When I tried to do something similar with my default backend which is MacOS and with the cairo backend it didnt work.

However when I switched to agg and TKagg and run your example the custom font was there.

Here is your code modified so that it runs on my machine

#!/usr/bin/env python
import matplotlib
matplotlib.use( "agg" )
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

fig, ax = plt.subplots()
prop = fm.FontProperties(fname='Outwrite.ttf')
ax.set_title('Text in a cool font', fontproperties=prop, size=40)
plt.show()
plt.savefig('test.png')

The resulting image is with a custom font.

entropiece
  • 389
  • 5
  • 10
  • 1
    This solved my problem on OSX Yosemite running an iPython notebook in a Python 3 conda environment. – wil3 Apr 20 '15 at 09:46
  • After switching to agg, using Ubuntu 20.04, I had to remove the font cache and then it worked! – smcs Jan 21 '22 at 14:13