svgforecast-fan
Forecast fan chart
Where is the series heading, and how uncertain is the forecast?
How to read it
- Read the line for history and where the forecast continues from.
- Read the bands: the darker is 80%, the lighter 95%.
- Bands that widen quickly mean the forecast is soon uncertain.
- Callout 1: The forecast's centre line.
- Callout 2: The lighter band: 95% prediction interval.
- Callout 3: History.
Watch out
- Intervals assume the future behaves like the past, so a structural change can break them.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
- Intervals are the model's prediction intervals (not confidence intervals for the mean); the forecast line starts at the last observed point so the hand-off is visible.
- Long histories are drawn with largest-triangle-three-buckets downsampling (1,500 points); the Data table keeps every row.
- Panel data (a series column) gets one small multiple per series, up to nine.
# Forecast fan chart — Codesplash Chart Lab (recipe "forecast-fan")
# 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-fan-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["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["actual", "fitted", "forecast"])
_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 levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
T = "month"
V = "passengers (thousands)"
KIND = "kind"
L80 = "lo 80"
H80 = "hi 80"
L95 = "lo 95"
H95 = "hi 95"
SER = None
d = df.dropna(subset=[T]).sort_values(T)
kind = d[KIND].astype(str).str.lower() if KIND else pd.Series("actual", index=d.index)
names = levels_of(d[SER]) if SER else [None]
fig, axes = plt.subplots(len(names), 1, figsize=(8, 3.4 * len(names)), squeeze=False)
for ax, name in zip(axes[:, 0], names):
m = pd.Series(True, index=d.index) if name is None else d[SER].astype(str) == str(name)
act, fit, fc = d[m & (kind == "actual")], d[m & (kind == "fitted")], d[m & (kind == "forecast")]
for lo, hi, a in ((L95, H95, 0.15), (L80, H80, 0.3)): # nested 95% and 80% prediction intervals
if lo and hi and len(fc):
ax.fill_between(fc[T], fc[lo], fc[hi], color=PALETTE[0], alpha=a, lw=0)
ax.plot(act[T], act[V], color=REF, linewidth=1.4, label="actual")
if len(fit):
ax.plot(fit[T], fit[V], color=PALETTE[1], linewidth=1, linestyle="--", label="fitted")
if len(fc):
joined = pd.concat([act.tail(1), fc]) # continue from the last observation
ax.plot(joined[T], joined[V], color=PALETTE[0], linewidth=2, label="forecast")
ax.set_title(str(name) if name is not None else V, fontsize=10)
ax.set_ylabel(V)
axes[0, 0].legend(fontsize=8, loc="upper left")
axes[-1, 0].set_xlabel(T)
fig.tight_layout()
plt.show()Needs pandas, numpy, matplotlib · reads forecast-fan-demo.csv · app theme from the optional codesplash helper
# Forecast fan chart — Codesplash Chart Lab (recipe "forecast-fan")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
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-fan-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["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["actual", "fitted", "forecast"])
_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 levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
T = "month"
V = "passengers (thousands)"
KIND = "kind"
L80 = "lo 80"
H80 = "hi 80"
L95 = "lo 95"
H95 = "hi 95"
SER = None
d = df.dropna(subset=[T]).sort_values(T)
kind = d[KIND].astype(str).str.lower() if KIND else pd.Series("actual", index=d.index)
names = levels_of(d[SER]) if SER else [None]
fig = make_subplots(rows=len(names), cols=1, subplot_titles=[str(n) if n is not None else "" for n in names])
for r, name in enumerate(names, start=1):
m = pd.Series(True, index=d.index) if name is None else d[SER].astype(str) == str(name)
act, fit, fc = d[m & (kind == "actual")], d[m & (kind == "fitted")], d[m & (kind == "forecast")]
for lo, hi, a, label in ((L95, H95, 0.15, "95%"), (L80, H80, 0.3, "80%")):
if lo and hi and len(fc):
fig.add_scatter(x=fc[T], y=fc[lo], mode="lines", line=dict(width=0), showlegend=False, hoverinfo="skip", row=r, col=1)
fig.add_scatter(x=fc[T], y=fc[hi], mode="lines", line=dict(width=0), fill="tonexty", fillcolor=rgba(PALETTE[0], a), name=label, showlegend=r == 1, row=r, col=1)
fig.add_scatter(x=act[T], y=act[V], mode="lines", line=dict(color=REF, width=1.5), name="actual", showlegend=r == 1, row=r, col=1)
if len(fit):
fig.add_scatter(x=fit[T], y=fit[V], mode="lines", line=dict(color=PALETTE[1], dash="dash", width=1), name="fitted", showlegend=r == 1, row=r, col=1)
if len(fc):
joined = pd.concat([act.tail(1), fc])
fig.add_scatter(x=joined[T], y=joined[V], mode="lines", line=dict(color=PALETTE[0], width=2), name="forecast", showlegend=r == 1, row=r, col=1)
fig.update_yaxes(title_text=V, row=r, col=1)
fig.show()Needs pandas, numpy, plotly · reads forecast-fan-demo.csv · app theme from the optional codesplash helper
# Forecast fan chart — Codesplash Chart Lab (recipe "forecast-fan")
# 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-fan-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[["kind"]] <- factor(df[["kind"]], levels = c("actual", "fitted", "forecast"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
t_col <- "month"
v_col <- "passengers (thousands)"
kind_col <- "kind"
l80 <- "lo 80"
h80 <- "hi 80"
l95 <- "lo 95"
h95 <- "hi 95"
ser_col <- NULL
d <- df[!is.na(df[[t_col]]), ]
num_or_na <- function(col) if (is.null(col)) NA_real_ else d[[col]]
d <- data.frame(t = d[[t_col]], v = d[[v_col]], kind = if (is.null(kind_col)) "actual" else tolower(as.character(d[[kind_col]])),
l80 = num_or_na(l80), h80 = num_or_na(h80), l95 = num_or_na(l95), h95 = num_or_na(h95),
ser = if (is.null(ser_col)) v_col else factor(as.character(d[[ser_col]]), levels = levels_of(d[[ser_col]])))
d <- d[order(d$ser, d$t), ]
act <- d[d$kind == "actual", ]; fc <- d[d$kind == "forecast", ]; fit <- d[d$kind == "fitted", ]
last_obs <- do.call(rbind, lapply(split(act, act$ser, drop = TRUE), function(s) s[nrow(s), ]))
fc_line <- rbind(last_obs, fc) # continue from the last observation
p <- ggplot(d, aes(t, v)) +
{ if (nrow(fc) && !all(is.na(fc$l95))) geom_ribbon(data = fc, aes(ymin = l95, ymax = h95), fill = cs_cat[1], alpha = 0.15) } +
{ if (nrow(fc) && !all(is.na(fc$l80))) geom_ribbon(data = fc, aes(ymin = l80, ymax = h80), fill = cs_cat[1], alpha = 0.3) } +
geom_line(data = act, colour = ref_col, linewidth = 0.6) +
{ if (nrow(fit)) geom_line(data = fit, colour = cs_cat[2], linetype = "dashed", linewidth = 0.5) } +
{ if (nrow(fc)) geom_line(data = fc_line, colour = cs_cat[1], linewidth = 0.9) } +
facet_wrap(~ser, ncol = 1, scales = "free_y") + labs(x = t_col, y = v_col) + theme_cs
print(p)Needs ggplot2 · reads forecast-fan-demo.csv · app theme from the optional codesplashr helper