今天才发现这个问题,两条曲线的数据是一致的,但是画出来却不同步,存在错位,如下图所示:
对应的Code:
def plot_deflection_local(name,label,data_frame):
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['figure.dpi'] = 200
fig,axs = plt.subplots(1,1)
axs.set(xlabel='日期',ylabel='挠度 (mm)',title=name)
local_max_value = data_frame['Val'][start_index:end_index].max()
local_min_value = data_frame['Val'][start_index:end_index].min()
axs.yaxis.set_ticks(np.linspace(local_min_value,local_max_value,8,endpoint=True))
deflection = axs.plot(data_frame['Val'][start_index:end_index],color='deepskyblue',linestyle='-',label='挠度',linewidth=0.7,alpha=0.8)
axs.axhline(local_max_value,color='r',ls='--',lw=0.8)
axs.axhline(local_min_value,color='g',ls='--', lw=0.8)
axs.grid()
#plt.xticks(pd.date_range(start=start_index,end=end_index,freq='20D'),pd.date_range(start=start_index,end=end_index,freq='20D').astype(str))
ax2=axs.twinx()#这是双坐标关键一步
temperature = ax2.plot(data_frame['Temp'][start_index:end_index],color='orange',linestyle='-',label='温度',linewidth=0.7,alpha=0.8)
ax2.set(ylabel=r'温度 ($^\circ$C)')
plt.xticks(pd.date_range(start=start_index,end=end_index,freq='20D'),pd.date_range(start=start_index,end=end_index,freq='20D').astype(str))
lines_plot = deflection+temperature
plt.legend(lines_plot, ['挠度','温度'],loc='lower center', fancybox=True, bbox_to_anchor=(0.5, -0.25),shadow=False, ncol=5)
fig.tight_layout()
plt.savefig(img_path+label+'_local.png')
怀疑是
plt.xticks(pd.date_range(start=start_index,end=end_index,freq='20D'),pd.date_range(start=start_index,end=end_index,freq='20D').astype(str))
这段代码的位置错了,让后调整到ax2=axs.twinx() 之前,结果也验证了猜想: