python画图,怎么让图例显示中文
时间: 2023-08-13 12:29:35 浏览: 507
您可以使用matplotlib库中的font_manager模块来让图例显示中文。具体的步骤如下:
1. 导入font_manager模块:
```
from matplotlib import font_manager
```
2. 创建一个FontProperties对象,用来设置中文字体。您可以指定中文字体的名称和大小。例如,如果您想要使用SimHei字体,大小为14,可以使用如下代码:
```
font = font_manager.FontProperties(fname='C:\\Windows\\Fonts\\SimHei.ttf', size=14)
```
其中,fname参数指定了中文字体文件的路径。这里的路径是Windows系统中SimHei字体文件的默认路径。如果您使用的是其他操作系统或者其他字体,需要将路径修改为相应的值。
3. 在legend函数中使用FontProperties对象来设置图例的字体。例如:
```
plt.legend(prop=font)
```
下面是一个完整的例子:
```
import matplotlib.pyplot as plt
from matplotlib import font_manager
x = [1, 2, 3, 4, 5]
y1 = [1, 2, 3, 4, 5]
y2 = [1, 4, 9, 16, 25]
plt.plot(x, y1, label='线性函数')
plt.plot(x, y2, label='二次函数')
plt.legend(loc='upper left')
# 设置中文字体
font = font_manager.FontProperties(fname='C:\\Windows\\Fonts\\SimHei.ttf', size=14)
plt.legend(prop=font)
plt.show()
```
这样就可以让图例显示中文了。
阅读全文
相关推荐
















