当前位置: 移动技术网 > IT编程>脚本编程>Python > Matplotlib折线图以及设置图例中文显示

Matplotlib折线图以及设置图例中文显示

2020年07月05日  | 移动技术网IT编程  | 我要评论

Talk in cheap,show code…

  • 我和同桌好友变化图
from matplotlib import pyplot as plt
from matplotlib import font_manager

age = list(range(11, 31))  # 年龄范围
y1 = [1, 0, 1, 1, 2, 4, 3, 2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]  # 代表自己
y2 = [0, 0, 0, 2, 3, 4, 3, 2, 3, 3, 3, 5, 7, 8, 8, 3, 3, 3, 1, 1]  # 代表同桌

# 设置展示图表的内容字体,可以从Windows字体里面拷贝字体文件到当前文件目录
my_font = font_manager.FontProperties(fname='msyh.ttc')

# 设置图片展示大小
plt.figure(figsize=(20, 8), dpi=80)

# 设置x轴坐标内容
xticks_labels = ["{}岁".format(a) for a in age]

# 设置背景网格
plt.grid(alpha=0.3, linestyle='-.')  # alpha表示透明度, linestyle表示线条风格

"""
label:表示图例代表的线条含义
linewidth:线条粗细
color: 线条颜色
alpha: 线条透明度
linestyle: 线条样式,
    有“:”、“--”、“-.”、“-”等 样式
"""
plt.plot(age, y1, label='自己', linewidth=5, color='r', alpha=0.3, linestyle='--')  #
plt.plot(age, y2, label='同桌', linestyle=':', color='green')

# 设置图例样式
plt.legend(loc='upper right', prop=my_font)  # loc代表图例所在的位置,upper right代表右上角

# 设置字体,x轴刻度,x轴刻度内容,旋转标签45°,设置中文字体显示
plt.xticks(age[::1], labels=xticks_labels, rotation=45, fontproperties=my_font)

# 折线图标题
plt.title('我和同桌11~30岁每年交友变化折线图', fontproperties=my_font)

# x轴标签(指的是x轴代表的含义,比如:岁数)
plt.xlabel('岁数', fontproperties=my_font)

# y轴标签(指的是y轴代表的含义,比如:交友数)
plt.ylabel('交友数', fontproperties=my_font)

# 展示图表数据
plt.show()

运行程序,得到图形如下所示:
在这里插入图片描述

本文地址:https://blog.csdn.net/zcm545186061/article/details/107121442

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网