19

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))
alodi
  • 666
  • 1
  • 6
  • 9

1 Answers1

26

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

tamasgal
  • 24,826
  • 18
  • 96
  • 135
  • This gives me `Arial`. findfont will just return the font file that closely matches the given fontproperty object. – alodi Jan 07 '15 at 11:17
  • Well, I thought your problem is determining the font if it's "unset", like "sans-serif". Since otherwise you simply use `matplotlib.rcParams['font.family']` – tamasgal Jan 07 '15 at 11:18
  • You understood the question correctly. I'm trying to find the unspecified font that hides behind `sans-serif`. But your code gives me `Arial` instead of `DejaVu Sans`. – alodi Jan 07 '15 at 11:22
  • OK, that seems quite weird, since `font_manager` is used to determine the font for plots… For me at least, it works fine. – tamasgal Jan 07 '15 at 11:23