Ben Lindsay Ben Lindsay - 1 year ago 101
Python Question

How can I configure matplotlib to be able to read fonts from a local path?

I would like to be able to place

files in a local folder and have Matplotlib configured to look in that folder for fonts if it can't find them in the normal system folders. This previous answer showed how to point to a specific font in any directory. Here's the code in the answer:

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager

path = '/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf'
prop = font_manager.FontProperties(fname=path)
mpl.rcParams[''] = prop.get_name()
fig, ax = plt.subplots()
ax.set_title('Text in a cool font', size=40)

The problem with this is that I would have to do this every time I want Helvetica (or in this case Comic Sans) in my plot. I believe another solution is to copy the ttf file into something like
, but I'd prefer not to touch that stuff and place files locally so they don't disappear when I update matplotlib, and so it's easier to sync my configuration across different machines. I feel like there should be some way to configure matplotlib in my
file so that if I use Helvetica I don't have to provide the path each time. How can I place a
file in a custom directory (or at least one that is safe against python or matplotlib updates) and not have to retype the file path every time I plot?

Bonus points if the solution allows me to use a path relative to the directory returned by
import matplotlib; matplotlib.get_configdir()
, since for some of my machines that is
and for some it's

Answer Source

In case anyone cares, I decided it's most convenient to just copy my .ttf files to the directory that looks something like ~/anaconda/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf. The files were still there after I updated matplotlib, so at least it will probably be a while before I will have to repeat the process, and this way I don't need to point to a directory or call a script every time I plot. If you do this and/or change your default font list in your matplotlibrc file (both of which I did) you'll probably have to delete your cache file located somewhere like ~/.matplotlib/fontList.cache or ~/.cache/matplotlib/fontList.cache`. Matplotlib will regenerate this next time you plot something.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download