Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plt.show() can find font, but plt.savefig() cannot

I need to use a required OTF font while plotting with matplotlib, but cannot figure out how to access it. I saw How to use a (random) *.otf or *.ttf font in matplotlib?, but neither recommended solution works for me.

Option 1, where I set prop = matplotlib.font_manager.FontProperties(fname = '/Users/<username>/Library/Fonts/Univers-Condensed.otf') spits an error immediately because the OTF font doesn't have the TTF structure expected.

Option 2, where I set the family name to the general name of the font, finds the OTF font:

plot_font = {'family' : 'Univers-Condensed',
             'size'   : '11'}

matplotlib.rc('font', **plot_font)

plt.plot(range(10))
plt.title('Show me Universe', size = 32)

plt.show()

Groovy! But when I change plt.show() to plt.savefig('test.pdf') I get this error:

UserWarning: findfont: Font family ['Univers-Condensed'] not found.
Falling back to Bitstream Vera Sans
  (prop.get_family(), self.defaultFamily[fontext]))

Why is plt.savefig() unable to find the same fonts that plt.show() CAN find? Do you have any recommendations for a different way to approach it? I'd prefer not to convert the fonts to TTF.

like image 326
Caroline Avatar asked Jan 19 '26 18:01

Caroline


1 Answers

I found this explanation this morning, which helps matplotlib find a family of fonts installed in the user profile. It's important to note that both ~/.matplotlib/fontList.py3k.cache AND ~/.matplotlip/tex.cache need to be cleared. I had only cleared ~/.matplotlib/fontList.py3k.cache during my initial tries.

I still haven't identified WHY plt.show() and plt.savefig() behaved differently when only one cache was cleared, but I am now able to save figures with the fonts that I want.

like image 134
Caroline Avatar answered Jan 22 '26 12:01

Caroline