使用matplotlib画同一子图共享x轴的图(以某地蒸发量与降水量及气温图为例)

直接上代码

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams["axes.unicode_minus"]=0
import numpy as np
month=np.arange(1,13,1)
d_p=[2.6,5.9,9,34,28,70,123,154,23,12,3,2]
d_e=[2.3,4.6,7,23.2,25.6,76.7,135.6,162.2,32.3,20,6.4,3.3]
d_t=[2,2.2,3.3,4.5,6.3,10.2,20.3,33.4,23,16.5,12,6.2]#录入数据
fig,ax=plt.subplots()#1*1的子图
bar_e=ax.bar(month,d_e,color="r",label="蒸发",alpha=0.9)
bar_p=ax.bar(month,d_p,color="green",label="降水",alpha=0.7)#画图
ax.set_ylabel("水")
ax.set_title("图片")
ax_r=ax.twinx()#共享x轴
line=ax_r.plot(month,d_t)#画折线图
ax_r.set_ylabel("气温")
plt.legend([bar_e,bar_p,line[0]],["蒸发","降水","气温"])#图例
plt.show()

猜你喜欢

转载自blog.csdn.net/m0_49040755/article/details/121356209
今日推荐