How to plot multiple seasonal_decompose plots in one figure?

╄→гoц情女王★ 提交于 2019-12-21 04:51:31

问题


I am decomposing multiple time series using the seasonality decomposition offered by statsmodels.Here is the code and the corresponding output:

def seasonal_decompose(item_index):
    tmp = df2.loc[df2.item_id_copy == item_ids[item_index], "sales_quantity"]
    res = sm.tsa.seasonal_decompose(tmp)
    res.plot()
    plt.show()

seasonal_decompose(100)

Can someone please tell me how I could plot multiple such plots in a row X column format to see how multiple time series are behaving?


回答1:


sm.tsa.seasonal_decompose returns a DecomposeResult. This has attributes observed, trend, seasonal and resid, which are pandas series. You may plot each of them using the pandas plot functionality. E.g.

res = sm.tsa.seasonal_decompose(someseries)
res.trend.plot()

This is essentially the same as the res.plot() function would do for each of the four series, so you may write your own function that takes a DecomposeResult and a list of four matplotlib axes as input and plots the four attributes to the four axes.

import matplotlib.pyplot as plt
import statsmodels.api as sm

dta = sm.datasets.co2.load_pandas().data
dta.co2.interpolate(inplace=True)
res = sm.tsa.seasonal_decompose(dta.co2)

def plotseasonal(res, axes ):
    res.observed.plot(ax=axes[0], legend=False)
    axes[0].set_ylabel('Observed')
    res.trend.plot(ax=axes[1], legend=False)
    axes[1].set_ylabel('Trend')
    res.seasonal.plot(ax=axes[2], legend=False)
    axes[2].set_ylabel('Seasonal')
    res.resid.plot(ax=axes[3], legend=False)
    axes[3].set_ylabel('Residual')


dta = sm.datasets.co2.load_pandas().data
dta.co2.interpolate(inplace=True)
res = sm.tsa.seasonal_decompose(dta.co2)

fig, axes = plt.subplots(ncols=3, nrows=4, sharex=True, figsize=(12,5))

plotseasonal(res, axes[:,0])
plotseasonal(res, axes[:,1])
plotseasonal(res, axes[:,2])

plt.tight_layout()
plt.show()




回答2:


import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = plt.figure()
ax1 = fig.add_subplot(2,3,1)
ax1.scatter(x, y)
ax2 = fig.add_subplot(2,3,2)
ax2.scatter(x, y)
ax3 = fig.add_subplot(2,3,3)
ax3.scatter(x, y)
ax4 = fig.add_subplot(2,3,4)
ax4.scatter(x, y)
ax5 = fig.add_subplot(2,3,5)
ax5.scatter(x, y)
ax6 = fig.add_subplot(2,3,6)
ax6.scatter(x, y)
plt.show()



来源:https://stackoverflow.com/questions/45184055/how-to-plot-multiple-seasonal-decompose-plots-in-one-figure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!