Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib can't find font installed in my Linux machine

I am trying to draw an xkcd-style plot with matplotlib (ver. 1.4.2) under Python 3.

When I try to run:

import matplotlib.pyplot as plt
plt.xkcd()
plt.plot([1,2,3,4], [1,4,9,16], 'bo')
plt.axis([0, 6, 0, 20])
plt.show()

It opens an empty window without any image and I get the error:

/usr/lib/python3/dist-packages/matplotlib/font_manager.py:1279: UserWarning: findfont: Font family ['Humor Sans', 'Comic Sans MS', 'StayPuft'] not found. Falling back to Bitstream Vera Sans
  (prop.get_family(), self.defaultFamily[fontext]))
/usr/lib/python3/dist-packages/matplotlib/font_manager.py:1289: UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=normal:variant=normal:weight=normal:stretch=normal:size=medium. Returning /usr/share/matplotlib/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf
  UserWarning) Exception in Tkinter callback

I have Humor Sans installed. I checked it with fc-list | grep Humor. It can also be used within other programs, like Libre Office. I also have staypuft installed. Isn't that enough?

The same code above but without the plt.xkcd() bit works flawlessly.

An alternative to plt.show(), like pylab.savefig() won't work either for the xkcd code, but doesn't have any problem with the same code without using xkcd.

like image 597
Pierre B Avatar asked Jun 20 '16 11:06

Pierre B


People also ask

Where are matplotlib fonts?

To map font names to font files, matplotlib has a dictionary (or json file) located in its cache directory. Note, this file is not always in the same place, but usually sits at the home directory.

How do I add fonts to matplotlib?

Install fonts on your system. Usually, double-click on the . ttf file and then click on the Install button in the window that pops up. Note that Matplotlib handles fonts in True Type Format (.

Where is matplotlib installed?

On Unix-like systems, this directory is generally located in your HOME directory under the . config/ directory.

What is the default matplotlib font?

Matplotlib needs fonts to work with its text engine, some of which are shipped alongside the installation. The default font is DejaVu Sans which covers most European writing systems.


2 Answers

If you add a new font after installing matplotlib then try to remove the font cache. Matplotlib will have to rebuild the cache, thereby adding the new font.

It may be located under ~/.matplotlib/fontList.cache or ~/.cache/matplotlib/fontList.json.

like image 143
Serenity Avatar answered Sep 20 '22 20:09

Serenity


For Mac User: try to run this command in python: (or before the .py file)

import matplotlib

matplotlib.font_manager._rebuild()
like image 40
Zhihui Shao Avatar answered Sep 20 '22 20:09

Zhihui Shao