Matplotlib,谷歌字体:如何在vscode jupyter笔记本中使用字体



我已经搜索了一段时间,试图在matplotlib直方图中使用中文字体。我没有在本地安装字体,而是尝试按照帖子使用Github中的原始TTF文件。然而,我收到了In FT2Font: Can not load face. Unknown file format.消息。这是我的代码:

from tempfile import NamedTemporaryFile
import urllib3
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
https = urllib3.PoolManager()
github_url = 'https://github.com/google/fonts/tree/main/ofl/notosanssc/NotoSansSC[wght].ttf'
url = github_url + '?raw=true' # will trigger the download
response = https.request('GET', url)
# print(response.data) # to confirm the successful response with data
f = NamedTemporaryFile(delete=False, suffix='.ttf')
f.write(response.data)
f.close()
f.name # C:\Users\<username>\AppData\Local\Temp\tmp9i1czwm1.ttf'
fig, ax = plt.subplots()
ax.plot([1, 2, 3])
prop = fm.FontProperties(fname=f.name)
ax.set_title('this is a special font:n%s' % github_url, fontproperties=prop)
ax.set_xlabel('This is the default font')
plt.show()

重新安装matplotlib并删除缓存并没有给我带来好运。可能是什么问题?谢谢

我已经用另一种方式而不是Github谷歌字体解决了这个问题。还有一篇关于在Mac上使用中文字体的帖子。然而,我使用的是Windows 10,它无法复制Mac的解决方案。

在Windows 10(或11(上,打开SettingsPersonalization,然后打开fonts。在这里,您可以确认已安装的字体和可用的中文字体。接下来,转到matplotlib字体缓存,它可能是C:Users<username>.matplotlib。有一个名为fontlist-<version>.json的文件,用于存储可用的字体。

格式为:

{
"_version": 330,
"_FontManager__default_weight": "normal",
"default_size": null,
"defaultFamily": {
"ttf": "DejaVu Sans",
"afm": "Helvetica"
},
ttflist: [
{
"fname": "C:\Windows\Fonts\FRABKIT.TTF",
"name": "Franklin Gothic Book",
"style": "italic",
"variant": "normal",
"weight": 400,
"stretch": "normal",
"size": "scalable",
"__class__": "FontEntry"
},
"__class__": "FontManager"
]
}

最后,您可以使用name字段设置字体系列。以下是片段:

fig, ax = plt.subplots()
fontP = matplotlib.font_manager.FontProperties()
fontP.set_family('DFKai-SB')
ax.set_title('職缺頻率計算', fontproperties=fontP)
plt.show()

最新更新