matplotlib.pyplot中文标题乱码

绘图的时候,部分原始代码如下,

plt.plot(x1,y1)
plt.xlabel("温度")
plt.ylabel("湿度")
plt.show()

结果如下,标题乱码
根据网上查询的结果是,matplotlib.pyplot在显示时无法找到合适的字体。 于是添加如下几行:
这里写图片描述

 from matplotlib.font_manager import FontProperties 
 font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=12)
 ....
 ....
plt.plot(x1,y1)
plt.xlabel("温度",fontproperties=font_set)
plt.ylabel("湿度",fontproperties=font_set)
plt.show() 

结果如下,仍然有乱码现象,在字符串前增加u,即虽然我开头已经有了,# -- coding:utf-8 -- ,但是这句是告诉python程序中的文本是utf-8编码,让python可以按照utf-8读取,中文前加u就是告诉python后面的是个unicode编码,存储时按unicode格式存储。或者将开头# -- coding: gbk --也可。
这里写图片描述

plt.plot(x1,y1)
plt.xlabel(u"温度",fontproperties=font_set)
plt.ylabel(u"湿度",fontproperties=font_set)
plt.show()

这样得出的结果才是我需要的:
这里写图片描述
另外:python编码格式这个文章有详细说明

猜你喜欢

转载自blog.csdn.net/bhcgdh/article/details/78568212