title: Matplotlib - 中文字体
categories:
- python
- Matplotlib
tags: - python
- Matplotlib
- Computer Drawing
首先,Matplotlib本身是不支持中文的。
因此我们需要自己下载中文字体;
方法:
使用思源黑体,思源黑体是 Adobe 与 Google 推出的一款开源字体。
下载地址:
官网:https://source.typekit.com/source-han-serif/cn/
Github地址:https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese

可以下载个 OTF 字体,比如 SourceHanSansSC-Bold.otf,将该文件文件放在当前执行的代码文件中:

import numpy as np
from matplotlib import pyplot as plt
import matplotlib
from matplotlib.font_manager import FontProperties
# fname 为 你下载的字体库路径,注意 SourceHanSansSC-Bold.otf 字体的路径
zhfont1 = FontProperties(fname="SourceHanSansSC-Bold.otf",size = 15)
x = np.arange(1, 11)
y = 2 * x + 5
plt.title("测试", fontproperties=zhfont1)
# fontproperties 设置中文显示,fontsize 设置字体大小
plt.xlabel("x 轴", fontproperties=zhfont1)
plt.ylabel("y 轴", fontproperties=zhfont1)
plt.plot(x, y)
plt.show()
运行结果:

本文介绍了如何在Matplotlib中显示中文。由于Matplotlib默认不支持中文,我们需要自行下载中文字体,例如思源黑体。下载后,将字体文件放置在代码执行目录,并在代码中指定使用该字体,从而实现中文的正确显示。
1320

被折叠的 条评论
为什么被折叠?



