svgforecast-components
Forecast by part
Which parts make up a neural forecast: how much is trend, how much is season, how much is detail?
How to read it
- Start with the top panel: the forecast itself, the sum of the parts below it.
- Read the first part as the level and its slow movement; it starts from the last observed value.
- Read each later part as a deviation around 0 that the network adds: a season, or finer detail.
Watch out
- Each panel has its own scale, so a part with a big-looking swing may be small: read sizes from the axis.
- Only an interpretable N-BEATS splits trend from season by design; the parts of a generic network carry no such meaning.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Each row is one part's contribution at one forecast step; the parts add up to the forecast, which is drawn on top as their sum.
- The first part carries the last observed value (the level the windows were centred on), so its panel reads in the series' units; later parts are deviations around 0.
- Each panel has its own vertical scale, so compare shapes across panels and read sizes from the axis.
Use with care
Only the interpretable N-BEATS stacks mean trend and seasonality; a generic network's blocks have no such meaning.
# Forecast by part — Codesplash Chart Lab (recipe "forecast-components")
# controls: defaults
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("forecast-components-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"])
df["part"] = pd.Categorical(df["part"].astype("string"), categories=["trend", "seasonality"])
_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")
T = "month"
V = "passengers (thousands)"
P = "part"
names = list(df[P].cat.categories) if hasattr(df[P], "cat") else list(dict.fromkeys(df[P].astype(str)))
wide = df.pivot_table(index=T, columns=P, values=V, aggfunc="last", observed=False).reindex(columns=names).sort_index()
total = wide.sum(axis=1, min_count=len(names)) # the forecast: the parts add up to it
fig, axes = plt.subplots(len(names) + 1, 1, figsize=(8, 1.9 * (len(names) + 1)), sharex=True, squeeze=False)
axes[0][0].plot(total.index, total.to_numpy(), color="black", linewidth=2, marker="o", markersize=3)
axes[0][0].set_title("Forecast (sum of the parts)", fontsize=9, loc="left")
for k, name in enumerate(names):
ax = axes[k + 1][0]
ax.plot(wide.index, wide[name].to_numpy(), color=PALETTE[k % len(PALETTE)], linewidth=1.6, marker="o", markersize=3)
if k > 0:
ax.axhline(0, color=REF, linewidth=0.8) # later parts are deviations around 0
ax.set_title(str(name), fontsize=9, loc="left")
fig.tight_layout()
plt.show()Needs pandas, numpy, matplotlib · reads forecast-components-demo.csv · app theme from the optional codesplash helper
# Forecast by part — Codesplash Chart Lab (recipe "forecast-components")
# controls: defaults
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("forecast-components-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"])
df["part"] = pd.Categorical(df["part"].astype("string"), categories=["trend", "seasonality"])
_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")
from plotly.subplots import make_subplots
T = "month"
V = "passengers (thousands)"
P = "part"
names = list(df[P].cat.categories) if hasattr(df[P], "cat") else list(dict.fromkeys(df[P].astype(str)))
wide = df.pivot_table(index=T, columns=P, values=V, aggfunc="last", observed=False).reindex(columns=names).sort_index()
total = wide.sum(axis=1, min_count=len(names))
fig = make_subplots(rows=len(names) + 1, cols=1, shared_xaxes=True, subplot_titles=["Forecast (sum of the parts)"] + [str(n) for n in names])
fig.add_trace(go.Scatter(x=total.index, y=total, mode="lines+markers", line=dict(color="black", width=2), name="forecast"), row=1, col=1)
for k, name in enumerate(names):
fig.add_trace(go.Scatter(x=wide.index, y=wide[name], mode="lines+markers", line=dict(color=PALETTE[k % len(PALETTE)]), name=str(name)), row=k + 2, col=1)
fig.update_layout(showlegend=False, height=200 * (len(names) + 1))
fig.show()Needs pandas, numpy, plotly · reads forecast-components-demo.csv · app theme from the optional codesplash helper
# Forecast by part — Codesplash Chart Lab (recipe "forecast-components")
# controls: defaults
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("forecast-components-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")
df[["part"]] <- factor(df[["part"]], levels = c("trend", "seasonality"))
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
T <- "month"
V <- "passengers (thousands)"
P <- "part"
names <- if (is.factor(df[[P]])) levels(droplevels(df[[P]])) else unique(as.character(df[[P]]))
d <- data.frame(t = df[[T]], v = df[[V]], part = as.character(df[[P]]))
total <- aggregate(v ~ t, data = d, FUN = sum) # the forecast: the parts add up to it
total$part <- "Forecast (sum of the parts)"
d <- rbind(total[, c("t", "v", "part")], d)
d$part <- factor(d$part, levels = c("Forecast (sum of the parts)", names))
p <- ggplot(d, aes(t, v, colour = part)) +
geom_line(linewidth = 0.6) + geom_point(size = 1) +
facet_wrap(~ part, ncol = 1, scales = "free_y") +
scale_colour_manual(values = c("black", cs_cat[seq_along(names)]), guide = "none") +
labs(x = T, y = V)
print(p)Needs ggplot2 · reads forecast-components-demo.csv · app theme from the optional codesplashr helper