【问题标题】:Why doesn't matplotlib use the .ttf font that I provide?为什么 matplotlib 不使用我提供的 .ttf 字体?
【发布时间】:2012-09-29 05:00:56
【问题描述】:

我正在尝试在 matplotlib 中使用 TTF 字体; .ttf 文件已下载并保存在我的机器上。我关注other instructions on this site 使用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()

【问题讨论】:

  • 尝试清除 mpl 目录中的字体缓存(例如,~/.matplotlib)
  • 我删除了mpl目录下的字体缓存文件。再次运行代码并没有改变结果。我会注意到它不仅使用特定的 *.ttf 字体 - 即使对于我的 mpl-data/fonts/ 目录中的字体,在 Font Manager 中设置不同的姓氏也不会改变绘图窗口中显示的内容。
  • 嗯。我能想到的唯一另一件事是将您的第 4 行更改为:prop = fm.FontProperties(fname='coolfont')
  • 也试过了,但没有运气。还是很疑惑。
  • 我遇到了同样的问题。我最终意识到我的 matplotlibrc 中有一行指定 text.usetex = True 我忘记设置为 False。

标签: python fonts matplotlib


【解决方案1】:

这是因为您使用的后端。

当我尝试对我的默认后端 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')

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

【讨论】:

  • 这解决了我在 OSX Yosemite 在 Python 3 conda 环境中运行 iPython 笔记本的问题。
  • 在使用 Ubuntu 20.04 切换到 agg 后,我不得不删除字体缓存,然后它才起作用!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
  • 2013-03-27
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 2013-10-27
相关资源
最近更新 更多