以后尝试将笔记搬到csdn上,希望能帮到有需要的人。
matplotlib的中文显示问题网上有很多答案,但自己在使用的时候,就算是参考了其他人的答案,也出了一些问题,特此记录一篇。
代码可以在jupyter notebook中运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import random import matplotlib.pyplot as plt %matplotlib inline # 生成绘图数据 # x1表示9.1-9.30;x2表示10.1-10.31 # y1表示9月份每天的平均气温;y2表示10月份每天的平均气温 x1 = range(30) x2 = range(31) y1 = [float(format(random.uniform(20, 30), '.1f')) for i in range(30)] y2 = [float(format(random.uniform(18, 25), '.1f')) for i in range(31)] plt.plot(x1, y1, label='9月') plt.plot(x2, y2, label='10月') plt.title('9、10月的平均气温变化') plt.xlabel('日期') plt.ylabel('温度') plt.legend(title='月份') |
生成图片:
此时会发现,图片中所有的中文都无法正常显示。一般可以采用两类方法:
- 方法一:导入font_manager,自定义myfont,然后在需要中文显示的语句中,将myfont传入即可。注意plt.legend()中参数和别的不同。
1 2 3 4 5 6 7 8 9 10 11 | from matplotlib import font_manager #fname后接字体的地址,我的字体是网上下载的黑体,默认是三个文件msyh.ttc、msyhbd.ttc、msyhl.ttc,任选一个 myfont = font_manager.FontProperties(fname='E:/Python数据分析/fonts/msyhl.ttc') plt.plot(x1, y1, label='9月') plt.plot(x2, y2, label='10月') plt.title('9、10月的平均气温变化', fontproperties=myfont) plt.xlabel('日期', fontproperties=myfont) plt.ylabel('温度', fontproperties=myfont) plt.legend(title='月份', prop=myfont) |
看图片会发现,该方法plt.legend()的title参数中的中文,仍然无法正常显示,我没有找到解决方法,有知道的小伙伴,可以留言,感激不尽!
- 方法二:设置font,将font传入matplotlib.rc()中
1 2 3 4 5 6 7 8 9 10 11 | import matplotlib font = {'family':'SimHei'} #font中还可以添加参数'weight':'bold', 'size':10 matplotlib.rc('font', **font) plt.plot(x1, y1, label='9月') plt.plot(x2, y2, label='10月') plt.title('9、10月的平均气温变化') plt.xlabel('日期') plt.ylabel('温度') plt.legend(title='月份') |
方法二优点:
- 只需要在开头设置好,代码中不需要设置其他参数;
- 所有的中文都可以显示。
方法二缺点:
- 有的系统可能不支持该方法(B站视频课老师讲的)
- 'family’后的字体名字一定要写对,否则也是不显示中文滴。
方法二也可以如下:为表述清晰,称为方法三
1 2 3 4 5 6 7 8 9 10 11 | # 显示中文sans-serif为matplotlib默认的字体,不支持中文 plt.rcParams['font.sans-serif'] = ['SimHei'] # 正常显示负号 plt.rcParams['axes.unicode_minus'] = False plt.plot(x1, y1, label='9月') plt.plot(x2, y2, label='10月') plt.title('9、10月的平均气温变化') plt.xlabel('日期') plt.ylabel('温度') plt.legend(title='月份') |
方法二设置成功后,jupyter notebook中的所有程序,中文都可以正常显示,需要重启一下,验证方法三,所以最后一张图的数据和其他的图片不同。
plt.legend()中的loc参数表示图例的位置,不设置时,会自动选择最好的位置。因此两张图片中,图例的位置也不同。