如何在一个图中绘制多个季节性分解图? [英] How to plot multiple seasonal_decompose plots in one figure?

查看:64
本文介绍了如何在一个图中绘制多个季节性分解图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 statsmodels 提供的季节性分解来分解多个时间序列.这是代码和相应的输出:

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)

有人可以告诉我如何以行 X 列格式绘制多个这样的图以查看多个时间序列的行为吗?

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?

推荐答案

sm.tsa.seasonal_decompose 返回 DecomposeResult .这有属性observedtrendseasonalresid,它们是pandas 系列.您可以使用pandas绘图功能来绘制它们中的每一个.例如.

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

这与 res.plot() 函数对四个系列中的每一个所做的基本相同,因此您可以编写自己的函数,该函数采用 DecomposeResult以及一个包含四个 matplotlib 轴的列表作为输入,并将四个属性绘制到四个轴上.

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

这篇关于如何在一个图中绘制多个季节性分解图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆