在同一figure同一图表绘制三个城市三条温度变化折线图
import matplotlib.pyplot as plt
import random
plt.rcParams['font.sans-serif'] = ['SimHei'] #显示中文
#创建figure
plt.figure(figsize = (20, 8), dpi = 80)
# 北京,上海,广州冬天11点到12的温度变化折线图
# 准备数据
x = range(60)
y_beijing = [random.uniform(1, 3) for i in x]
y_shanghai = [random.uniform(15, 20) for i in x]
y_guangzhou = [random.uniform(20, 25) for i in x]
# 绘制折线图
plt.plot(x, y_shanghai, color = 'b', linestyle = '-', label = '上海')
plt.plot(x, y_beijing, color = 'r', linestyle = '--', label = '北京')
plt.plot(x, y_guangzhou, color = 'g', label = '广州')
#修改刻度
y_ticks = range(40)
x_ch = ["11点{}分".format(i) for i in x]
plt.xticks(x[::5], x_ch[::5])
plt.yticks(y_ticks)
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("北京,上海,广州冬天11点到12的温度变化折线图")
plt.legend(loc='best')
plt.show()
同一figure不同图表绘制不同城市的一条温度变化折线图
import matplotlib.pyplot as plt
import random
plt.rcParams['font.sans-serif'] = ['SimHei']
#创建两行两列的figure
fig, ax = plt.subplots(nrows = 2, ncols = 2, figsize = (20, 8))
# 准备数据
x = range(60)
y_guangzhou = [random.uniform(20, 25) for i in x]
y_shanghai = [random.uniform(10, 15) for i in x]
y_beijing = [random.uniform(1, 3) for i in x]
#绘制折线图
ax[0][0].plot(x, y_guangzhou, color = 'r', label='广州')
ax[0][1].plot(x, y_shanghai, color = 'b', label = "上海")
ax[1][0].plot(x, y_beijing, color = 'g', label = '北京')
#修改刻度
x_ch = ["11点{}分".format(i) for i in x]
y_ticks = range(35)
ax[0][0].set_xticks(x[::5], x_ch[::5])
ax[0][1].set_xticks(x[::5], x_ch[::5])
ax[1][0].set_xticks(x[::5], x_ch[::5])
ax[0][0].set_yticks(y_ticks[::5])
ax[0][1].set_yticks(y_ticks[::5])
ax[1][0].set_yticks(y_ticks[::5])
ax[0][0].set_xlabel("时间")
ax[0][0].set_ylabel("温度")
ax[0][1].set_xlabel("时间")
ax[0][1].set_ylabel("温度")
ax[1][0].set_xlabel("时间")
ax[1][0].set_ylabel("温度")
ax[0][0].set_title("广州11点到12点的温度变化")
ax[0][1].set_title("上海11点到12点的温度变化")
ax[1][0].set_title("北京11点到12点的温度变化")
ax[0][0].legend(loc = 'upper left')
ax[0][1].legend(loc = 'upper left')
ax[1][0].legend(loc = 'upper left')
plt.show()