Python中使用matplotlib库绘图中如何给图形的图例设置中文字体显示

问题:当使用matplotlib绘图时遇到绘图,图例显示不出来中文字体

解决方式:

1)加载字体管理库

from matplotlib.font_manager import FontProperties

2)设置系统上字体的路径

font = FontProperties(fname="C:\\Windows\\Fonts\\simsun.ttc")

一般win11的字体在上述所述的路径下。simsun为宋体

3)绘制图形后设置坐标轴的标签

ax0.set_ylabel('中文1', fontproperties=font)

4)绘制图形时设置图例

ax0.plot(data['y'],label='图例名称:1、图例1  2、图例2)
ax0.legend(loc='upper right',prop=font)

测试结果: