Python matplotlib 字体管理器使用替代字体

3

我想在matplotlib中使用替代字体。通过使用font_manager,我可以让诸如xlabel,ylabel或title之类的东西工作,但我无法弄清楚如何更改行标签的字体。

我选择了"Phosphate.ttc"字体,因为它很容易被发现。


import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

def lineChart():
    my_font = fm.FontProperties(fname='/Library/Fonts/Phosphate.ttc')
    day = ('1','2','3')
    line1 = (10,20,30)
    line2 = (30,20,10)

    fig, ax = plt.subplots()
    ax.plot(day, line1, label='this goes to default font')
    ax.plot(day, line2, label='this is default font too')
    ax.legend(loc='upper center')
    plt.title('title display correct', fontproperties=my_font)
    plt.xlabel('xlabel display correct', fontproperties=my_font)
    plt.ylabel('ylabel display correct', fontproperties=my_font)
    plt.savefig("font_test.png")

if __name__ == '__main__':
    lineChart()

有没有一种全局设置备用字体的方法?(不需要将其安装到 matplotlib 模块路径中)

或者设置行标签以使用备用字体?

操作系统:OSX
Python 版本:3.6.4
matplotlib 版本:2.1.1

谢谢


我之前看过那篇帖子。它是通过rcParams设置字体系列,而不是使用完全不同的字体(不存在于matplotlib自己的字体目录中)。或者有一种方法可以注册新字体吗?我尝试了fm.FontProperties = fm.FontProperties(fname='/Library/Fonts/Phosphate.ttc'),但似乎matplotlib不喜欢它。 - Rui Li
好的,我不确定通过删除显示的注释是否会移除重复标志,但我会尝试。 - Thomas Kühn
请注意,管理员:我标记了这个问题为重复,但是OP指出建议的重复并没有解决他的问题,所以我的标记可能不合理。因此下面也是答案。 - Thomas Kühn
1个回答

2
您可以在legend命令中设置字体。将相应的行更改为:
ax.legend(loc='upper center', prop=my_font)

生成以下图片:

带有自定义字体的图例

编辑:

更改刻度标签的字体可以按照以下方式完成(在绘图命令之后添加):

for tick in ax.xaxis.get_major_ticks():
    tick.label.set_fontproperties(my_font)

for tick in ax.yaxis.get_major_ticks():
    tick.label.set_fontproperties(my_font)

结果看起来像这样:

带有自定义字体的勾选框


ax.legend(prop=my_font) 看起来没有包含“day”;ax.plot(day, ...) 中的字体也是“默认”的。 - Rui Li
@RuiLi 你是指xtick和ytick标签吗? - Thomas Kühn
是的。我记得在 Stack Overflow 上看到过有关 xticks 和 yticks 字体设置的内容。但不知为何现在找不到了。 - Rui Li
我在 https://matplotlib.org/api/text_api.html#matplotlib.text.Text 上找到了这个信息。在 set_xticklabels 中,它接受 **kwargs,其中一个关键字是 fontproperties。 - Rui Li
@RuiLi 很好。另外,查看我的答案编辑以获取另一种方法。 - Thomas Kühn

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