【问题标题】:Find out which font matplotlib uses找出 matplotlib 使用的字体
【发布时间】:2015-03-05 06:09:19
【问题描述】:

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

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

编辑:

警告可以直接通过

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

【问题讨论】:

    标签: python matplotlib fonts


    【解决方案1】:

    获取字体系列:

    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 将只返回与给定 fontproperty 对象密切匹配的字体文件。
    • 好吧,我认为您的问题是确定字体是否“未设置”,例如“无衬线”。否则你只需使用matplotlib.rcParams['font.family']
    • 您正确理解了这个问题。我试图找到隐藏在sans-serif 后面的未指定字体。但是你的代码给了我Arial 而不是DejaVu Sans
    • 好吧,这看起来很奇怪,因为font_manager 用于确定绘图的字体……至少对我来说,它工作正常。
    猜你喜欢
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    相关资源
    最近更新 更多