STL 分解
月次の製造業売上高をトレンド、季節成分、残差に分解します。

STL(Loess を用いた季節・トレンド分解)は、時系列を 観測値 = トレンド + 季節成分 + 残差 として表します。各パネルは時間軸を共有しますが縦軸のスケールはそれぞれ異なるため、各パネル左側の灰色のバー(データ単位ではすべて同じ長さ)が各成分の実際の大きさを示します。バーが短ければその成分が支配的であり、長ければその成分は小さいことを意味します。
設定は Warin (2024, Technology Innovations in Statistics Education) で、カナダ統計局のオープンな経済データを統計学の授業で活用する方法を扱っており、月次の製造業売上高は典型的な教材用の系列です。ここでのデータは説明のために シミュレーション したもので、カナダ統計局の数値ではありません。製造業売上高に似た系列(単位は 10 億ドル)で、2005 年 1 月から 2023 年 12 月まで(228 か月)、2 つの落ち込み(2009 年と 2020 年春)を含むトレンド、固定した月別パターン、ノイズから作っています。同じシミュレーション系列を STL、SARIMA、季節サブシリーズの例で使っています。分解には周期 12 か月、ロバスト推定の statsmodels.tsa.seasonal.STL を用い、サブタイトルには Wang, Smith & Hyndman (2006) の定義によるトレンドと季節性の強さを示しています。
コードおよび図中のテキストは英語です。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from statsmodels.tsa.seasonal import STL
# Simulated data, set in the context of Warin (2024) [warin2024statcan]
# Data: simulated monthly manufacturing sales, billions of dollars, 2005–2023 (shared generator)
rng = np.random.default_rng(2024)
idx = pd.date_range("2005-01-01", "2023-12-01", freq="MS")
t = np.arange(len(idx))
trend = 48 + 0.06 * t - 7 * np.exp(-((t - 54) / 9) ** 2) - 8 * np.exp(-((t - 183) / 2.5) ** 2)
season = np.tile([-3.0, -0.8, 2.6, 0.6, 1.2, 2.2, -3.4, -1.2, 1.6, 2.0, 0.4, -2.2], len(idx) // 12)
sales = pd.Series(trend + season + rng.normal(0, 0.7, len(idx)), index=idx)
res = STL(sales, period=12, robust=True).fit()
parts = {"Observed": sales, "Trend": res.trend, "Seasonal": res.seasonal, "Remainder": res.resid}
colors = ["#1D1D1F", "#007AFF", "#FF9500", "#8E8E93"]
# Strength of trend and seasonality (0 = none, 1 = all the variation)
f_trend = max(0, 1 - res.resid.var() / (res.trend + res.resid).var())
f_seas = max(0, 1 - res.resid.var() / (res.seasonal + res.resid).var())
fig, axes = plt.subplots(4, 1, figsize=(9, 7.5), sharex=True,
gridspec_kw=dict(height_ratios=[1.4, 1, 1, 1]))
bar = 2 * res.resid.abs().max() # common scale bar, in billions of dollars
x0 = sales.index[0] - np.timedelta64(400, "D")
for ax, (name, s), c in zip(axes, parts.items(), colors):
if name == "Remainder":
ax.vlines(s.index, 0, s, color=c, lw=0.8)
ax.axhline(0, color="#C7C7CC", lw=0.8)
else:
ax.plot(s.index, s, color=c, lw=2 if name == "Trend" else 1)
ax.set_ylabel(name, rotation=0, ha="right", va="center", labelpad=14)
# Scale bar: same height in billions in every panel
mid = (s.max() + s.min()) / 2
ax.plot([x0, x0], [mid - bar / 2, mid + bar / 2], color="#C7C7CC", lw=5, solid_capstyle="butt",
clip_on=False)
axes[-1].set_xlabel("Year")
fig.align_ylabels(axes)
axes[0].set_xlim(x0 - np.timedelta64(200, "D"), sales.index[-1])
slump = res.trend.diff(12).idxmin().year # steepest yearly fall
low = res.seasonal.groupby(res.seasonal.index.month_name()).mean().idxmin() # weakest month
axes[0].set_title(f"Manufacturing sales: the {slump} slump, and a dip every {low}", pad=26)
axes[0].text(0, 1.04, f"STL, period 12, robust · n = 228 months (simulated) · strength: trend = "
f"{f_trend:.2f}, seasonality = {f_seas:.2f} · grey bars = {bar:.1f} bn",
transform=axes[0].transAxes, fontsize=9.5, color="#6E6E73")
plt.show()
図にはオプションの PyStatlas スタイル を使用しています。同じ見た目にするには plt.style.use("pystatlas.mplstyle") を追加してください。
データの出典
- Simulated data. Simulated data with a fixed random seed, created for this example.
No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work. - Warin (2024), Statistics Canada's open economic data for teaching. Warin, T. (2024). Access Statistics Canada's open economic data for statistics and data science courses. Technology Innovations in Statistics Education, 15(1). https://doi.org/10.5070/t5.1868
The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not Statistics Canada's figures.
これらの例は統計手法を説明するためのものです。項目に別の記載がない限り数値はシミュレーションであり、図のタイトルはこのシミュレーションデータで図が示す内容を述べたものです。引用した論文の知見でも、実質的な問いに対する著者の立場でもありません。結果、背景、データについては、ここに挙げた論文を参照してください。
引用方法
PyStatlas は Thierry Warin が作成・運営しています。研究や業務に役立った場合は、ぜひ引用してください。
Warin, T. (2026). STL decomposition. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/time-series/stl-decomposition/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
version = {1.1.0},
howpublished = {\url{https://warin.ca/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}