在Ubuntu中导入Open Sans字体到matplotlibrc失败

5 投票
1 回答
2514 浏览
提问于 2025-04-18 06:58

我尝试在我的项目中使用字体 Open Sans

import matplotlib as mpl
#update matplotlibrc
mpl.rcParams['font.family'] = 'Open Sans'

#testplot
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.title('Everything is crazy!!!', size=32)
plt.show()

但是当我想要绘图时,matplotlib 找不到这个字体,出现了类似这样的错误信息:

/usr/lib/pymodules/python2.7/matplotlib/font_manager.py:1236: UserWarning: findfont: Font family ['Open Sans'] not found. Falling back to Bitstream Vera Sans
      (prop.get_family(), self.defaultFamily[fontext]))

/usr/lib/pymodules/python2.7/matplotlib/font_manager.py:1246: UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=normal:variant=normal:weight=light:stretch=normal:size=medium. Returning /usr/share/matplotlib/mpl-data/fonts/ttf/cmb10.ttf
      UserWarning)

这个字体已经在我的 Ubuntu 系统上安装好了,而且所有的 OpenSans-*.ttf 文件也都复制到了 matplotlib 的文件夹里(在 Ubuntu 中是 /usr/share/matplotlib/mpl-data/fonts/ttf/)。请问有什么办法可以在 matplotlibrc 文件中使用这个字体吗?

1 个回答

3

好的,这个问题虽然老旧,但我刚刚安装了Open Sans字体,以便在Matplotlib中使用:

提问者(OP)已经按照正确的步骤操作,但需要强制让Matplotlib重新生成字体缓存。最简单的方法是:

from matplotlib import font_manager
font_manager._rebuild()

需要注意的是,在Linux系统上,除了上面提到的字体路径,Matplotlib似乎还会在~/.fonts文件夹中搜索字体,所以你可以把字体安装到那里。

撰写回答