[英]Matplotlib, Google Fonts: how to use fonts in vscode jupyter notebook
我搜索了一段时间,试图在我的 matplotlib 直方图中使用中文字体。 我没有在本地安装字体,而是尝试按照帖子使用来自 Github 的原始 TTF 文件。 但是,我得到了In FT2Font: Can not load face. Unknown file format.
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 Google 字体找到了它。 还有一篇关于在 Mac 上使用中文字体的帖子。 但是,我使用的是 Windows 10,它无法复制 Mac 的解决方案。
在 Windows 10(或 11)上,打开Settings
、 Personalization
,然后打开fonts
。 在这里可以确认安装的fonts和可用的中文fonts。 接下来,go 到 matplotlib 字体缓存,可以是C:\Users\<username>\.matplotlib
有一个名为fontlist-<version>.json
的文件,存储了可用的 fonts。
格式为:
{
"_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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.