Search code examples
pythonpython-3.xmatplotlibseabornubuntu-server

Python3 fonts for matplotlib running on headless server


I wrote a python3 (3.4.3) script that generates some graphs using matplotlib and seaborn, and it works wonderfully on my laptop running ubuntu 14.04.

I want to schedule it to run as a cron job on my server, which is running ubuntu-server.

To get it to run at all, I had to change the matplotlib backend with matplotlib.use("Agg")

The script now runs fine, but matplotlib can't find some fonts:

/usr/lib/python3/dist-packages/matplotlib/font_manager.py:1236:UserWarning: findfont: 
Font family ['sans-serif'] not found. Falling back to Bitstream Vera Sans
(prop.get_family(), self.defaultFamily[fontext]))

/usr/lib/python3/dist-packages/matplotlib/font_manager.py:1246: UserWarning: findfont: 
Could not match :family=Bitstream Vera Sans:style=normal:variant=normal:weight=normal:stretch=normal:size=10.0.
Returning /usr/share/matplotlib/mpl-data/fonts/ttf/cmtt10.ttf
UserWarning)

The substitute fonts are quite ugly, and I have not been able to figure out how to install the fonts that are used by matplotlib/seaborn by default.

How do I install the default fonts? Easy solutions (e.g. using apt-get or pip are preferred).


Solution

  • The easiest solution I found was to download the font as a .ttf and set matplotlib to use that ttf:

    fontprop = matplotlib.font_manager.FontProperties(fname = "path/fontname.ttf")
    matplotlib.rcParams['font.family'] = fontprop.get_name()