ax.twiny() 具有日期时间格式

ax.twiny() with a datetime format

我有这个代码:

from datetime import timedelta
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
  

gfg = np.array(np.datetime64('2019-08-26 18:00'))
forecast_time = []
forecast_time.append(gfg)
df_forecast_time = pd.DataFrame(forecast_time)
forecast_data = []
forecast_data.append(0)
for i in range(1,10):
    df_forecast_time=df_forecast_time.append(df_forecast_time.loc[i-1]+timedelta(hours=1),ignore_index=True)
    forecast_data.append(i)

forecast_time_arr = np.array(df_forecast_time)
forecast_data_arr = np.array(forecast_data)

event_time = np.array(np.datetime64('2019-08-27 01:25'))
lead_time = []
lead_time.append(event_time)
df_lead_time = pd.DataFrame(lead_time)
for i in range(1,5):
    df_lead_time=df_lead_time.append(df_lead_time.loc[i-1]+timedelta(hours=-1),ignore_index=True)

lead_time_arr = np.array(df_lead_time)

##################################
fig=plt.figure()
plt.plot(forecast_time_arr,forecast_data_arr)

ax = plt.gca()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))

ax.set_xlim([forecast_time_arr[0],forecast_time_arr[-1]]) 

plt.xlabel('Forecast time')
plt.ylabel('Forecast data')

plt.vlines(event_time, forecast_data_arr[0], forecast_data_arr[-1], color='red')

plt.grid(True, color = "grey", linewidth = ".4", linestyle = "-.")

这使得这个数字:

但是,我需要添加一个包含“提前期”的顶轴,即红线的时间 -1、-2、-3 ... 小时,如下所示:

但是我 运行 解决了定位第二个 x 轴刻度的问题,因为它们是日期时间...

感谢任何提示!

如果我正确理解你的问题,建议使用 secondary_xaxis。将此添加到您的代码底部:

def date2lead(x):
    return (x - mdates.date2num(event_time)) * 24


def lead2date(x):
    return (x / 24 + mdates.date2num(event_time))

sec = ax.secondary_xaxis('top', functions=(date2lead, lead2date))
sec.set_xlabel('Lead time [h]')

请注意,如果您需要在提前期 space 中绘制数据,我会添加到您的 event_time 并在日期时间 space 中绘制。