找出Matplotlib使用的字体

19

我正在寻找一种简单的方法来获取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)

这使我感到

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

我可以看出在这台机器上,matplotlib.pyplot使用DejaVu Sans。 不过,我认为应该有更简单的方法来获取这些信息。

编辑:

警告可以直接通过以下方式触发:

matplotlib.font_manager.findfont(matplotlib.font_manager.FontProperties(family=font))
1个回答

26
获取字体系列:

To obtain the font family:

->

获取字体系列:

matplotlib.rcParams['font.family']

如果是像“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'

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


这会给我Arial字体。findfont将返回最接近给定字体属性对象的字体文件。 - alodi
好的,我认为您的问题是确定字体是否为“未设置”,例如“sans-serif”。否则,您可以使用 matplotlib.rcParams ['font.family'] - tamasgal
你理解问题的意思了。我正在尝试找到隐藏在“sans-serif”后面的未指定字体。但是你的代码给出的是“Arial”,而不是“DejaVu Sans”。 - alodi
好的,这似乎相当奇怪,因为font_manager用于确定绘图所使用的字体...对我来说至少它正常工作。 - tamasgal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接