找出matplotlib使用的字体

alo*_*odi 12 python fonts matplotlib

我正在寻找一种很好的方法来获取matplotlib.pyplot使用的默认字体的名称.该文档表明该字体是从rcParams ['font.family']中的列表中选择的,该列表按优先级自上而下排序.我的第一次尝试是检查警告,即,

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)
Run Code Online (Sandbox Code Playgroud)

这给了我

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
Run Code Online (Sandbox Code Playgroud)

我可以说,在这台机器上,dejaVu Sans被matplotlib.pyplot使用.但是,我认为应该有一种更简单的方法来获取这些信息.

编辑:

警告可以直接通过触发

matplotlib.font_manager.findfont(matplotlib.font_manager.FontProperties(family=font))
Run Code Online (Sandbox Code Playgroud)

tam*_*gal 14

要获得字体系列:

matplotlib.rcParams['font.family']
Run Code Online (Sandbox Code Playgroud)

如果它是'sans-serif'这样的通用字体系列,请使用fontfind以查找实际字体:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

我在以下单元测试中发现了这个font_manager:https: //github.com/matplotlib/matplotlib/blob/4314d447dfc7127daa80fa295c9bd56cf07faf01/lib/matplotlib/tests/test_font_manager.py