找出matplotlib使用哪种字体 [英] Find out which font matplotlib uses

查看:264
本文介绍了找出matplotlib使用哪种字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

这给了我

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. 但是,我认为应该有一种更简单的方法来获取这些信息.

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.

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

The warning can be triggered directly via

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

推荐答案

要获取字体系列:

matplotlib.rcParams['font.family']

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

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'

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

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

这篇关于找出matplotlib使用哪种字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆