Skip to content
svgforecast-fan

Forecast fan chart

Where is the series heading, and how uncertain is the forecast?

Demo data · seed 20261101 · 156 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read the line for history and where the forecast continues from.
  2. Read the bands: the darker is 80%, the lighter 95%.
  3. Bands that widen quickly mean the forecast is soon uncertain.
  1. Callout 1: The forecast's centre line.
  2. Callout 2: The lighter band: 95% prediction interval.
  3. 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