gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:27:45 25 4
gpt4 key购买 nike

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()

问题:我想要一月、二月、三月等所有月份的股票行情。应提及年份,如 2016 年、2017 年等,月份应在中间加上小勾号。

错误:

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

最佳答案

您的问题是您试图更改 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

关于python - 时间序列季节性分解中的次刻度轴和主刻度轴 matplotlib 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60053561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com