noob
noob

Reputation: 3811

Position of title on TIME Series seasonality plots

df

Date        Col1   Col2   Col3
2019-11-1    12     13     14
2019-10-1    2      3      1
2019-03-01   2      1      1 
and so on

Code to decompose time series to get seasonality, trends, observed and residual values:

 df = df.set_index('Date')
 from statsmodels.tsa.seasonal import seasonal_decompose

 for cols in df.columns.values:
    s_dec_multiplicative = seasonal_decompose(df[cols], model = 
    "multiplicative")
    s_dec_multiplicative.plot()
    plt.title(cols)
    plt.show()

Now as output I am getting graphsenter image description here

The problem with these graphs is that I am getting title above Residual graph as shown in pic. I need the title to be above observed graph

Upvotes: 1

Views: 2388

Answers (1)

Josmoor98
Josmoor98

Reputation: 1811

I made some fake data, which is hopefully representative. I'm sure (hope) there is a better way to achieve this.

# imports
import pandas as pd
import numpy as np
from statsmodels.tsa.seasonal import seasonal_decompose
import matplotlib.pyplot as plt

Then form the fake data.

# random data
np.random.seed(0)
data = np.random.randint(1, 10, [50, 3])

# dates 
start = pd.datetime(2019, 11, 1)
end = start + pd.DateOffset(days=data.shape[0] - 1)

# dummy dataframe
df = pd.DataFrame(
    data, 
    index = pd.date_range(start, end), 
    columns = ['col_one', 'col_two', 'col_three']
)

Then using the following, you can control which graph has the title. You can access DecomposeResult attributes, these are given in attr below.

attr = ['observed', 'trend', 'seasonal', 'resid']

for col in df:
    fig, ax = plt.subplots(len(attr), 1, sharex=True)
    sd = seasonal_decompose(df[col], model = "multiplicative")

    for idx, a in enumerate(attr):
        s_attr = getattr(sd, a)
        s_attr.plot(ax = ax[idx], title = col if idx == 0 else None)
        ax[idx].set(ylabel= a)

enter image description here


Edit

Added the ylabels.

enter image description here

Upvotes: 3

Related Questions