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()

运行结果:
在这里插入图片描述

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐