Im looking for a nice way to get the name of the default font that is used by matplotlib.pyplot. The documentation indicates that the font is selected from the list in rcParams['font.family'] which is ordered top down by priority. My first try was to check for warnings, i.e.,
import matplotlib.pyplot as plt
import warnings
for font in plt.rcParams['font.sans-serif']:
print font
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
plt.rcParams['font.family'] = font
plt.text(0,0,font)
plt.savefig(font+'.png')
if len(w):
print "Font {} not found".format(font)
which gives me
Bitstream Vera Sans
Font Bitstream Vera Sans not found
DejaVu Sans
Lucida Grande
Font Lucida Grande not found
Verdana
Geneva
Font Geneva not found
Lucid
Font Lucid not found
Arial
Helvetica
Font Helvetica not found
Avant Garde
Font Avant Garde not found
sans-serif
I can tell that on this machine, DejaVu Sans is used by matplotlib.pyplot. However, I thought there should be an easier way to obtain this information.
Edit:
The warning can be triggered directly via
matplotlib.font_manager.findfont(matplotlib.font_manager.FontProperties(family=font))
The default font has changed from "Bitstream Vera Sans" to "DejaVu Sans".
You can set the fontsize argument, change how Matplotlib treats fonts in general, or even changing the figure size.
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. If you are on mac (windows), it usually sits at whereever your HOME (%HOME%) environmental variable is set to.
To get a list of all the fonts currently available for matplotlib, we can use the font_manager. findSystemFonts() method.
To obtain the font family:
matplotlib.rcParams['font.family']
If it's a general font family like 'sans-serif', use fontfind
to find the actual font:
>>> from matplotlib.font_manager import findfont, FontProperties
>>> font = findfont(FontProperties(family=['sans-serif']))
>>> font
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/mpl-data/fonts/ttf/Vera.ttf'
I found this in the unit tests of the font_manager
:
https://github.com/matplotlib/matplotlib/blob/4314d447dfc7127daa80fa295c9bd56cf07faf01/lib/matplotlib/tests/test_font_manager.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With