Reputation: 16089
I’m writing a Python program that uses matplotlib. I’d like to use a font that isn’t included with matplotlib. (Well, I want to use Lucida Grande, which is included in OS X, but matplotlib can’t read the .dfont file directly so I need to distribute my own .ttf font.)
It seems like matplotlib only ever looks in one directory for fonts: mpl-data/fonts
. It’s possible to tweak matplotlib’s configuration to change where the mpl-data
directory is, but it doesn’t seem to be possible to specify more than one such directory in which fonts may be found. Is that accurate?
(It would be possible for me to put the font in my system’s global mpl-data
directory, but it feels wrong for an application to muck around with a globally-used directory like that. And I sure as hell don’t want to include the entire mpl-data
-plus-one-file with my application.)
Upvotes: 3
Views: 137
Reputation: 2931
One possibility is to expand on the response provided here which uses the matplotlib font manager module. Specifically, it looks like you can specify the absolute path to your font with the fname
argument to matplotlib.font_manager.FontProperties
(see the docs here: http://matplotlib.org/api/font_manager_api.html#matplotlib.font_manager.FontProperties)
Modifying the previous SO response (to a slightly simpler question) below, this is certainly worth a try if you can specify the absolute path to the ttf font file in your workflow. I've used a built-in MacOS font below (and that works), but maybe try substituting your particular absolute path & font to see if it works.
import matplotlib
matplotlib.use( "agg" ) #some backend sensitivity explained in previous SO response
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
fig, ax = plt.subplots()
#specify the absolute path to your font file:
absolute_path_to_ttf_file = '/opt/X11/share/fonts/TTF/VeraSe.ttf'
prop = fm.FontProperties(fname=absolute_path_to_ttf_file)
ax.set_title('Text in a cool font', fontproperties=prop, size=40)
plt.show()
plt.savefig('test.png')
Upvotes: 2