时间序列季节性分解中的小刻度轴和主刻度轴matplotlib格式

时间:2020-02-04 08:43:41

标签: python pandas matplotlib

df

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

用于分解时间序列以获取季节性,趋势,观测值和残差值的代码:

from statsmodels.tsa.seasonal import seasonal_decompose
from matplotlib import dates as mdates
years = mdates.YearLocator()    # only print label for the years
months = mdates.MonthLocator()  # mark months as ticks
years_fmt = mdates.DateFormatter('%Y')
fmt = mdates.DateFormatter('%b')

df = df.set_index('Date')


s_dec_multiplicative = seasonal_decompose(df['Col1'], model = "multiplicative")
s_dec_multiplicative.plot()

s_dec_multiplicative.xaxis.set_major_locator(years)
s_dec_multiplicative.xaxis.set_minor_locator(months)
s_dec_multiplicative.xaxis.set_major_formatter(years_fmt)
s_dec_multiplicative.xaxis.set_minor_formatter(fmt)
plt.show()

问题:我希望所有月份的JAN,FEB,MAR等股票行情类似。应该提到年份,例如2016年,2017年,依此类推,月份之间应有小刻度。

错误:

---> 12 s_dec_multiplicative.xaxis.set_major_locator(years)
AttributeError: 'DecomposeResult' object has no attribute 'xaxis'

1 个答案:

答案 0 :(得分:2)

您的问题是您正在尝试更改DecomposeResult对象的属性,而应该在ax对象上工作。

让我们检索一些玩具时间序列数据:

from pandas_datareader import data
goog = data.DataReader("GOOG", "yahoo")["Adj Close"]
goog.plot();

enter image description here

现在让我们进行所需的分解,并将结果放入Pandas' df

from statsmodels.tsa.seasonal import seasonal_decompose
s_dec_multiplicative = seasonal_decompose(goog, model = "multiplicative", freq=12)

observed = s_dec_multiplicative.observed
seasonal = s_dec_multiplicative.seasonal
residual = s_dec_multiplicative.resid

df = pd.DataFrame({"observed":observed, "seasonal":seasonal,"residual":residual}

最后,我们准备绘制:

from matplotlib import dates as mdates
years = mdates.YearLocator()    # only print label for the years
months = mdates.MonthLocator()  # mark months as ticks
years_fmt = mdates.DateFormatter('%Y-%b')
fmt = mdates.DateFormatter('%b')

_, axes = plt.subplots(nrows=3,ncols=1, figsize=(20, 10))
for i, ax in enumerate(axes):
    ax = df.iloc[:,i].plot(ax=ax)
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(years_fmt)
    ax.xaxis.set_minor_locator(months)
    ax.xaxis.set_minor_formatter(fmt)
    ax.set_ylabel(df.iloc[:,i].name)
    plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)
    plt.setp(ax.xaxis.get_majorticklabels(), rotation=90)

enter image description here