Matplotlibrc 中的字体

Fonts in Matplotlibrc

对于我遇到的问题的任何见解,我将不胜感激。

我最近将 python 3 下载到我的 MacBook Pro 上。我有一个示例 python 脚本,我在其中绘制了一些曲线,并尝试从终端命令行使用 python 3 运行 这个脚本。在从命令行 运行 运行脚本之前,我对控制绘图外观的 matplotlibrc 文件进行了一些更改。

具体来说,我通过编写 font.family : sans-serifmatplotlibrc 文件中的 font.family 选项设置为 sans-serif。我有这个的原因是因为我想要 Avant Garde 字体,所以在文件中我也有 font.sans-serif : Avant Garde

但是,当我使用 python3 script.py 从终端命令行 运行 脚本时,我收到以下错误消息:

findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.
findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.
findfont: Font family ['sans'] not found. Falling back to DejaVu Sans.
findfont: Font family ['sans'] not found. Falling back to DejaVu Sans.
findfont: Font family ['sans'] not found. Falling back to DejaVu Sans.

因此生成的绘图不显示无衬线、Avant Garde 字体中的文字。

我试过在终端命令行中使用 pip3 install fonts,但这没有帮助。

如有任何帮助,我将不胜感激。

你能不能检查一下 matplotlib 是否知道你的字体存在这些行

import matplotlib.font_manager
matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')

如果没有显示所需的字体,您必须将其添加到 ~/Library/Fonts/

注意:必须是ttf文件

总结问题下方的大量评论:

在通过 rcParams 指定要使用的字体时,使用 准确的 字体名称很重要。在这个具体案例中,问题是即使字体名称在系统上下文菜单中显示为 Avant Garde Normal,它的真实名称是 AvantGarde Normal(没有第一个空格)。

这个如果知道字体的文件名就可以查到。在这种情况下

import matplotlib.font_manager
fp = matplotlib.font_manager.FontProperties(fname=r"Absolute\Path\to\fonts\AVANTN.TTF")
print(fp.get_name())

因此在rc参数文件中需要指定

font.sans-serif : AvantGarde Normal