2012-10-08 28 views
7

我想在matplotlib中使用TTF字体; .ttf文件被下载并在我的机器上本地存在。我跟着other instructions on this site选择使用font_manager的字体;但是,我尝试使用字体属性的任何文本仍然以默认的matplotlib字体显示。为什么matplotlib不使用我提供的.ttf字体?

我知道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() 
+1

尝试清除mpl目录中的字体缓存(例如〜/ .matplotlib) –

+0

我删除了mpl目录中的字体缓存文件。再次运行代码不会改变结果。我会注意到,它不仅仅使用特定的* .ttf字体 - 即使是在我的mpl-data/fonts /目录中的字体,在Font Manager中设置不同的系列名称也不会改变出现在绘图窗口中的内容。 – kwill

+0

嗯。只有其他的东西我能想到的是改变你的第四行:'prop = fm.FontProperties(fname ='coolfont')' –

回答

4

因为你使用的是后端的。

当我试图做一些类似于我的默认后端MacOScairo后端它没有工作。

但是,当我切换到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') 

产生的图像是使用自定义字体上。

+1

这解决了我在OSX Yosemite在Python 3 conda环境中运行iPython笔记本的问题。 – wil3

相关问题