5

I have a temp DF that has the following data in it

Quarter
2016Q3    146660510.0
2016Q4    123641451.0
2017Q1    125905843.0
2017Q2    129656327.0
2017Q3    126586708.0
2017Q4    116804168.0
2018Q1    118167263.0
2018Q2    121633740.0
2018Q3    125314447.0
2018Q4    120994896.0
2019Q1    126124709.0
2019Q2    134753318.0

I'm passing this into seasonal_decompose as quarterly data as per below but I get an error messsage saying "Axis must have freq set to convert to Periods". Frequency has been set in the DF. I think the issue is related to the fact you have to specify to matplotlib that the x axis is periods but I don't know how to do that and can't find any other examples where a DecomposeResult object with quarters is used

result = seasonal_decompose(temp, model='additive',period=4)  
result.plot()
plt.show()
Al___
  • 51
  • 1
  • 3

2 Answers2

5

Just convert your PeriodIndex to a DatetimeIndex, that will solve the issue:

    df.index = df.index.to_timestamp()
jpaniagua26
  • 49
  • 1
  • 4
  • This is a workaround, but not really an answer. According to the documentation of seasonal_compose this should work as in the code of the OP, shouldn't it? – fotis j Jan 06 '22 at 01:37
1
 date=['2016Q3'
 ,'2016Q4'
 ,'2017Q1'
 ,'2017Q1'
 ,'2017Q3'
 ,'2017Q4'
 ,'2018Q1'
 ,'2018Q3'
 ,'2018Q3'
 ,'2018Q4'
 ,'2019Q1'
 ,'2019Q2']

 data=[146660510.0
 ,123641451.0
 ,125905843.0
 ,129656327.0
 ,126586708.0
 ,116804168.0
 ,118167263.0
 ,121633740.0
 ,125314447.0
 ,120994896.0
 ,126124709.0
 ,134753318.0]

 df=pd.DataFrame({'date':date,'data':data})
 df['date']=pd.to_datetime(df['date'])
 df=df.set_index('date')
 ax=df.plot(figsize=(14,2))
 plt.show()

 decomposition=sm.tsa.seasonal_decompose(x=df['data'],model='additive',      extrapolate_trend='freq', period=3)

 decomposition_trend=decomposition.trend
 ax= decomposition_trend.plot(figsize=(14,2))
 ax.set_xlabel('Date')
 ax.set_ylabel('Trend of time series')
 ax.set_title('Trend values of the time series')
 plt.show()

 decomposition_residual=decomposition.resid
 ax= decomposition_residual.plot(figsize=(14,2))
 ax.set_xlabel('Date')
 ax.set_ylabel('Residual of time series')
 ax.set_title('Residual values of the time series')
 plt.show()
Golden Lion
  • 3,840
  • 2
  • 26
  • 35
  • This example helped me but I don't understand one part. I have monthly data and I was setting the period to 12 and receive the error. After seeing your example I set the period to 11 and it works just fine. How is the period set? Is it always points in a year minus 1? – MECoskun Apr 09 '23 at 22:01
  • documentation: Period of the series. Must be used if x is not a pandas object or if the index of x does not have a frequency. Overrides default periodicity of x if x is a pandas object with a timeseries index. – Golden Lion Apr 10 '23 at 14:41
  • In my example I am intrepolating 3 data points at a time for the frequency. – Golden Lion Apr 10 '23 at 15:00