Find out which font matplotlib uses

2019-03-25 10:33发布

问题:

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))

回答1:

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