svgstl-decomposition
Seasonal decomposition
How much of the series is trend, how much a repeating season, and what is left?
How to read it
- Read the top panel for the raw series.
- Read Trend for the long-run direction and Seasonal for the repeating shape.
- Read Remainder last: structure left there means the decomposition missed something.
- Callout 1: Observed: the series as measured.
- Callout 2: Trend: the long-run path.
- Callout 3: Seasonal: the repeating shape.
- Callout 4: Remainder: what's left; it should look like noise.
Watch out
- Compare panel scales: a seasonal panel can look strong while being small relative to the trend.
Defaults
- Multiplicative (remainder around 1)
- Off
- Treat seasonal and remainder parts as ratios around 1, not differences around 0.
Pinned in the code
- Components are drawn as the engine returned them (statsmodels STL ≡ R stl, or R decompose); nothing is re-estimated here.
- Each panel has its own y scale: compare shapes across panels, and sizes by reading the axes.
- The remainder is drawn as spikes from 0 (additive) or 1 (multiplicative); gaps are the classical trend's missing ends.
# Seasonal decomposition — Codesplash Chart Lab (recipe "stl-decomposition")
# controls: multiplicative=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("stl-decomposition-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def ordered(d, x, cols):
"""Rows with the needed values, sorted by the time column (stable); row order when there is none."""
d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
return d.sort_values(x, kind="stable") if x else d
def time_of(d, x):
return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "month"
OBS = "sales"
TR = "trend"
SE = "seasonal"
RE = "remainder"
MULT = False # remainder around 1 for a multiplicative decomposition
d = ordered(df, X, [OBS, TR, SE, RE])
t = time_of(d, X)
fig, axes = plt.subplots(4, 1, figsize=(8, 7), sharex=True)
for ax, col, name in zip(axes, [OBS, TR, SE, RE], ["Observed", "Trend", "Seasonal", "Remainder"]):
if name == "Remainder":
base = 1.0 if MULT else 0.0
ax.vlines(t, base, d[col], color=PALETTE[0], alpha=0.7, linewidth=1)
ax.axhline(base, color="grey", linewidth=0.8)
else:
ax.plot(t, d[col], color="black" if name == "Observed" else PALETTE[0], linewidth=1.2 if name == "Observed" else 1.6)
ax.set_ylabel(name, fontsize=9)
axes[-1].set_xlabel("month")
fig.tight_layout()
plt.show()Needs pandas, numpy, matplotlib · reads stl-decomposition-demo.csv · app theme from the optional codesplash helper
# Seasonal decomposition — Codesplash Chart Lab (recipe "stl-decomposition")
# controls: multiplicative=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("stl-decomposition-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def ordered(d, x, cols):
"""Rows with the needed values, sorted by the time column (stable); row order when there is none."""
d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
return d.sort_values(x, kind="stable") if x else d
def time_of(d, x):
return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "month"
OBS = "sales"
TR = "trend"
SE = "seasonal"
RE = "remainder"
MULT = False
from plotly.subplots import make_subplots
d = ordered(df, X, [OBS, TR, SE, RE])
t = time_of(d, X)
fig = make_subplots(rows=4, cols=1, shared_xaxes=True, subplot_titles=["Observed", "Trend", "Seasonal", "Remainder"])
fig.add_scatter(x=t, y=d[OBS], mode="lines", line=dict(color="black", width=1.2), row=1, col=1)
fig.add_scatter(x=t, y=d[TR], mode="lines", line=dict(color=PALETTE[0], width=1.6), row=2, col=1)
fig.add_scatter(x=t, y=d[SE], mode="lines", line=dict(color=PALETTE[0], width=1.6), row=3, col=1)
base = 1.0 if MULT else 0.0
fig.add_bar(x=t, y=d[RE] - base, base=base, marker_color=PALETTE[0], row=4, col=1)
fig.update_layout(showlegend=False, height=650)
fig.show()Needs pandas, numpy, plotly · reads stl-decomposition-demo.csv · app theme from the optional codesplash helper
# Seasonal decomposition — Codesplash Chart Lab (recipe "stl-decomposition")
# controls: multiplicative=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("stl-decomposition-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- "month"
obs <- "sales"
tr <- "trend"
se <- "seasonal"
re <- "remainder"
MULT <- FALSE
d <- ordered(df, x_col, c(obs, tr, se, re))
t <- time_of(d, x_col)
panel <- c("Observed", "Trend", "Seasonal", "Remainder")
long <- data.frame(t = rep(t, 4), value = c(d[[obs]], d[[tr]], d[[se]], d[[re]]), panel = factor(rep(panel, each = nrow(d)), levels = panel))
base <- if (MULT) 1 else 0
p <- ggplot(long, aes(t, value)) +
geom_line(data = long[long$panel != "Remainder", ], colour = cs_cat[1], linewidth = 0.7) +
geom_segment(data = long[long$panel == "Remainder", ], aes(xend = t, y = base, yend = value), colour = cs_cat[1], alpha = 0.7) +
facet_wrap(~panel, ncol = 1, scales = "free_y") + labs(x = "month", y = NULL) + theme_cs
print(p)Needs ggplot2 · reads stl-decomposition-demo.csv · app theme from the optional codesplashr helper