学习matplotlib的一天
目标:从单个绘图区改成多个绘图区

import random
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] #防止中文乱码
#定义数据
x = range(60)
y_1 = [random.uniform(15,18) for i in x]
#定义多组数据
y_2 = [random.uniform(3,8) for i in x]
#创建画步(**fig_kw: figsize:指定图的长度;dpi:图形清晰度dot per inch)
#plt.figure(figsize=(20,8),dpi=100) #默认(nrow = 1, ncols = 1, **fig_kw) 一行一列
figure, axes = plt.subplots(nrows = 2, ncols = 1, figsize = (20,8), dpi = 100)
#绘制图像
#'-'/无 实线、'--' 虚线。
#plt.plot(x, y_1, linestyle = '--',color = 'blue', label = '图例1') #'b'也可以 添加效果顺序随意
#
axes[0].plot(x, y_1, linestyle = '--',color = 'blue', label = '图例1')
axes[1].plot(x, y_2, color = 'r', label = '图例2')
#显示图例legend(loc=1~6 #每个数字表示不同位置,没有默认最佳 )
#plt.legend()
axes[0].legend() #显示图1
axes[1].legend() #显示图2
#修改x坐标的显示名称
x_label = ["11点{}分".format(i) for i in x]
# (x范围,步长)
#plt.xticks(x[::5],x_label[::5])
#plt.yticks(range(0,40,5))
axes[0].set_xticks(x[::5])
axes[0].set_xticklabels(x_label[::5])
axes[0].set_yticks(range(0,40,5))
axes[1].set_xticks(x[::5])
axes[1].set_xticklabels(x_label[::5])
axes[1].set_yticks(range(0,40,5))
# 添加网格(线条风格,透明度)
#plt.grid(linestyle = "--",alpha = 0.5)
axes[0].grid(linestyle = "--",alpha = 0.5)
axes[1].grid(linestyle = "--",alpha = 0.5)
#添加坐标标题
axes[0].set_xlabel("图1横坐标名称")
axes[0].set_ylabel("图1纵坐标名称")
axes[0].set_title("图1标题名称")
axes[1].set_xlabel("图2横坐标名称")
axes[1].set_ylabel("图2纵坐标名称")
axes[1].set_title("图2标题名称")
# 保存图片。 注意放在show之前,show()会释放figure资源,因此放后面不会显示
#plt.savefig("test.png")
#显示图片
plt.show()
冲冲冲~💪
1943





