python实现缺失时刻空缺的温度时间序列间断折线图和填充图绘制

1.python实现代码

from matplotlib import pyplot as plt
import pandas as pd
import datetime as dt
import matplotlib.dates as mdate
import numpy as np
random_data=pd.DataFrame(np.random.randint(-20,41,(49,5))) #生成一个49行5列的随机二维温度数组
random_time=pd.date_range('20200101','20200103',freq='1H')
all_time_data=pd.concat([pd.DataFrame(random_time),random_data],axis=1,)  #生成连续时间数据
all_time_data.columns=["time","100hpa","200hpa","500hpa","850hpa","1000hpa"]
data=all_time_data.drop(all_time_data.index[[8, 12, 30,31,32,33,40,42]])#剔除某几行时间数据
data.reset_index(drop=True, inplace=True)
time=data.time  #读取剩余时间
# 处理缺失时刻
t_complete = np.full((49, 5), np.nan)  # 生成(49,5)的二维空数组数据
time_indices = [random_time.tolist().index(t) for t in time]  # 获取已知时间对应的索引
t_complete[time_indices] = data.iloc[:,1:6]  # 将已知数据赋给空数组数据
final_data=pd.DataFrame(t_complete,columns=data.columns[1:6])

fig = plt.figure(figsize=(5,4),dpi=600,facecolor="w") 
#绘制单层时间序列温度折线图
ax1=plt.subplot(2,1,1)
ax1.plot(random_time,final_data["100hpa"],color='r',linewidth=0.5,linestyle='-')
ax1.set_ylabel('Temperature ( $^degree$C )',fontdict=fontdict)
ax1.tick_params(axis='both',which="major",length=3,width=1.0,color="k",direction='in',labelsize=6)
ax1.tick_params(top='in', right='in', which='both')
ax1.set_yticks(range(-20,41, 10))
ax1.set_xticks(random_time[::3])  #按间隔取时间刻度
ax1.set_xticklabels(random_time[::3],rotation=30)
ax1.xaxis.set_major_formatter(mdate.DateFormatter('%d/%H'))#时间显示格式

ax=plt.subplot(2,1,2)
# 绘制填充图
lev = [100,200,500,850,1000]
X, Y = np.meshgrid(random_time,lev)
tick=np.arange(-20,41,10)
t_contourf=ax.contourf(X, Y, t_complete.T, levels=np.arange(-20,41,1), cmap='jet')
#画colorbar,并指定位置,宽,高
cb = fig.colorbar(t_contourf,ticks=tick,pad=0.01)#,,
cb.ax.tick_params(left=True,direction="in",width=.2,labelsize=6,length=0,)
cb.ax.tick_params(which="minor",right=False)
cb.set_label('Temperature ( $^degree$C )',fontdict=fontdict)
ax.set_yticks(ticks=[100,250,500,850,1000],fontdict=fontdict)
ax.invert_yaxis()   #翻转y轴
ax.set_ylabel('Pressure ( hPa )',fontdict=fontdict)  
ax.tick_params(axis='both',which="major",length=4,width=1.0,color="k",direction='in',labelsize=6)
ax.tick_params(top='in', right='in', which='both')
ax.set_xticklabels(random_time[::3],rotation=30)
ax.xaxis.set_major_formatter(mdate.DateFormatter('%d/%H'))
ax.set_xlabel('Time',fontdict=fontdict)

plt.show()

2.绘图结果