Home > Software engineering >  ax.twiny() with a datetime format
ax.twiny() with a datetime format

Time:11-19

I have this code:

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 = "-.")

that makes this figure: enter image description here

However, I need to add a top axis that would contain the "lead time", which is the time of the red line -1, -2, -3 ... hours, like this: enter image description here

But I run into the problem of getting the second x-axis ticks positioned, due to the fact that they are datetime...

thanks for any tip!

CodePudding user response:

Suggest using secondary_xaxis if I understand your problem correctly. Add this to the bottom of your code:

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]')

secondary axis on top

Note that if you need to plot data in lead-time space, I'd just add to your event_time and plot it in datetime space.

  • Related