为什么matplotlib不使用我提供的.ttf字体?

kwi*_*ill 7 python fonts matplotlib

我正在尝试在matplotlib中使用TTF字体; .ttf文件已下载并在我的机器上本地存在.我已按照本网站上的其他说明选择使用的字体font_manager; 但是,我生成的任何试图使用字体属性的文本仍然以默认的matplotlib字体显示.

我知道Python确实成功找到了字体文件,因为prop.get_name()类似的命令确实显示了我想要的字体的属性 - 但这不是我的图中出现的.有什么建议?

举个例子:

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

fig, ax = plt.subplots()

prop = fm.FontProperties(fname='/Users/smith/fonts/coolfont.ttf')
ax.set_title('Text in a cool font', fontproperties=prop, size=40)

fig.show()
Run Code Online (Sandbox Code Playgroud)

ent*_*ece 6

这是因为您正在使用的后端。

当我尝试对我的默认后端执行类似的操作时,它MacOS不起作用cairo

但是,当我切换到aggTKagg运行您的示例时,自定义字体就在那里。

这是您修改后的代码,以便它在我的机器上运行

#!/usr/bin/env python
import matplotlib
matplotlib.use( "agg" )
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

fig, ax = plt.subplots()
prop = fm.FontProperties(fname='Outwrite.ttf')
ax.set_title('Text in a cool font', fontproperties=prop, size=40)
plt.show()
plt.savefig('test.png')
Run Code Online (Sandbox Code Playgroud)

生成的图像具有自定义字体。