Matplotlib 中文乱码解决方案 - 图表标题、坐标轴标签显示中文
在matplotlib中,标签出现中文乱码的原因是因为默认情况下matplotlib不支持中文字符集,需要手动设置字体才能正常显示中文。以下是一种简单的解决方案:
- 安装中文字体
在Linux系统中,可以通过以下命令安装中文字体:
sudo apt-get install fonts-wqy-zenhei
- 设置字体
在绘图前,需要设置字体,可以使用如下代码:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['WenQuanYi Zen Hei']
plt.rcParams['axes.unicode_minus']=False
其中,font.sans-serif参数指定字体,axes.unicode_minus参数用于解决负号显示问题。在这里,我们使用了文泉驿正黑字体,可以根据需要替换成其他中文字体。
- 示例代码
以下是一个简单的示例代码,演示如何解决中文乱码问题:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['WenQuanYi Zen Hei']
plt.rcParams['axes.unicode_minus']=False
# 绘制图形
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]
plt.plot(x, y)
plt.title('示例图形')
plt.xlabel('横轴')
plt.ylabel('纵轴')
plt.show()
在上述代码中,我们使用了plt.title、plt.xlabel、plt.ylabel函数添加了中文标签。运行代码后,应该可以正确显示中文字符集。
原文地址: https://www.cveoy.top/t/topic/oWKw 著作权归作者所有。请勿转载和采集!