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