Categories
matplotlib wiki

Changing the sans-serif font to Helvetica

I’m come right out with it; I hate the default font in matplotlib. It looks like a lazy, squished Helvetica, so why not change it to Helvetica. This is, however, a bit harder than I thought. 

I found this post but Mac fonts are now a different format (.ttc not .dfont).

1. Get Helvetica as a True Type font 

On my Mac running Mojave, Helvetica is found here

$ ls /System/Library/Fonts/Helvetica.ttc

The post above used fondu to convert the (now out-dated) Helvetica.dfont to Helvetica.ttf. Instead I converted this file to Helvetica.ttf using this website Online font converter. Don’t really like using these anonymous websites, but it seemed to work.

2. Find out where your matplotlib fonts live

$ python -c 'import matplotlib ; print(matplotlib.matplotlib_fname())'

/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc

(mine is here because I installed matplotlib using macports.)

3. Copy the Helvetica file into place

$ sudo cp Helvetica.ttf /opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/ttf/

4. Edit your matplotlibrc

You might have one in ~/.matplotlib/matplotlibrc as well.

$ sudo emacs /opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc

Find this line 

#font.sans-serif : DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Helvetica, Lucid, Arial, Avant Garde, sans-serif

and uncomment it and promote Helvetica to first place

font.sans-serif : Helvetica, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Avant Garde, sans-serif

5. Delete the matplotlib font caches

$ cd ~/.matplotlib
$ rm fontlist*

6. Test it (this will also recompile the font caches)

$ python -v -c 'import matplotlib.pyplot as plt;fig, ax = plt.subplots();ax.plot([1, 2, 3, 4]);ax.plot([1, 2, 3, 4]); fig.savefig("graph-line.pdf")'

And voila, Helvetica.


By Philip Fowler

Philip W Fowler is a computational biophysicist studying antimicrobial resistance working at the John Radcliffe Hospital in Oxford.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.