如何在一个图中绘制多个季节分解图?

2024-05-29 03:38:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用statsmodels提供的季节性分解来分解多个时间序列

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)

enter image description here

有人能告诉我如何用一行X列的格式绘制多个这样的图,看看多个时间序列的表现吗?


Tags: idindexdef时间res序列itemloc
2条回答

sm.tsa.seasonal_decompose返回一个DecomposeResult。它有属性observedtrendseasonalresid,这是熊猫系列。您可以使用pandas plot功能来绘制它们中的每一个。E、 g

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

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

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

enter image description here

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

enter image description here

相关问题 更多 >

    热门问题