matplotlib显示中文
在 matplotlib 中显示中文需要以下步骤:
- 安装中文字体
matplotlib 默认不支持中文字体,需要安装对应的字体。以 Windows 系统为例,可以在网上下载中文字体,将字体文件(.ttf 或 .otf 格式)放在系统字体库中(一般为 C:\Windows\Fonts 目录下)。
- 设置 matplotlib 字体
在代码中设置 matplotlib 的字体,例如:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置中文字体为黑体
其中 font.sans-serif 为 matplotlib 中的一个参数,用来设置无衬线字体。对于 Windows 系统,常用的中文字体有宋体(SimSun)、黑体(SimHei)等。
- 使用中文标签
在绘制图形时使用中文标签,例如:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置中文字体为黑体
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel('横轴标签')
plt.ylabel('纵轴标签')
plt.title('图形标题')
plt.show()
其中 xlabel, ylabel 和 title 都是 matplotlib 中的函数,用来设置标签和标题。在这些函数中使用中文标签即可
原文地址: https://www.cveoy.top/t/topic/gIvd 著作权归作者所有。请勿转载和采集!