python - 找出 matplotlib 使用的字体

标签 python matplotlib fonts

我正在寻找一种很好的方法来获取 matplotlib.pyplot 使用的默认字体的名称。 documentation表示字体是从 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

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

编辑:

警告可以直接通过

触发
matplotlib.font_manager.findfont(matplotlib.font_manager.FontProperties(family=font))

最佳答案

获取字体系列:

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

关于python - 找出 matplotlib 使用的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27817912/

相关文章:

python - 在 Eclipse 中配置 Pydev 解释器以使用 Enthought Python Distribution

python - 防止在 Django 模型中删除

python - matplotlib:(xx-small、x-small、small、medium、large、x-large、xx-large、large、smaller)特殊尺寸的值

c++ - 不使用 GDI 的 DirectX 字体教程

pdf - TrueType 字体无法从 SSRS 正确呈现为 pdf

c - 用C在屏幕上绘制字体

python - ImportError : Module use of python27. dll 与此版本的 Python 冲突

python - 用于近似像素颜色变化的嵌套 For 循环的 Numpy 等效项

python - Matplotlib rcParams 无法识别 "Times New Roman"(mac High Sierra)

python - 如何中止创建的协程Python