pythonpandasmatplotlibgluonts

avxspan with pandas period_range


I'm using gluonts and trying to adapt one of the examples to plot my data. I'm not overly proficient with pandas (I mostly use polars now) and I'm having an issue with the code below - this is basically cut/paste from gluonts code (i.e. gluonts.dataset.util.to_pandas in particular).

plt.axvspan errors with IncompatibleFrequency: Input has different freq=15T from PeriodIndex(freq=T) which I don't think is the case because both inputs to axvspan are Period(..., '15T').

Any ideas how to fix this, I suspect pandas or matplotlib may have changed since the gluonts example was created. A difference though is the glounts samples use daily not high-frequency data.

import pandas as pd
import numpy as np

timestamps = pd.period_range(start=pd.Period('2024-01-01 00:00', freq='15T'), periods=7*96, freq='15T')
data = np.random.rand(len(timestamps))
series = pd.Series(
        data,
        index=timestamps,
    )
series.plot()
plt.axvspan(timestamps[0], timestamps[0] + 96, facecolor="red", alpha=0.2)

Edit: pretty much right after posting this I discovered that the following works:

plt.axvspan(timestamps[0].to_timestamp(), (timestamps[0] + 96).to_timestamp(), facecolor="red", alpha=0.2)

Not sure if it's the best way but it's a way...


Solution

  • This is more elegant in my opinion:

    plt.axvspan(timestamps[0].start_time, 
                timestamps[0].start_time + pd.Timedelta(minutes=15*96), 
                facecolor="red", alpha=0.2)
    

    The timestamps[0] already has a start_time property that you can access, therefore there's no need to use .to_timestamp(). Also, adding 96 alone doesn't mean anything if you don't specify that it is a time difference. I added the multiplication of 15 since each step that you have is 15 minutes.