svgfevd
Forecast error variance decomposition
How much of each series' forecast uncertainty comes from shocks to each series, at each horizon?
How to read it
- Read each panel as one series' forecast uncertainty at each horizon.
- Read the band widths as the share due to each shock.
- A series explained mostly by its own shocks at long horizons takes little from the others.
Watch out
- The split depends on the order of the series, so try another order before reading much into small shares.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Shares of Σ_{i<h} (Θ_i)² at each horizon h, using the same Cholesky ordering as the impulse responses; the shares at each horizon sum to 100%.
- A series explained almost entirely by its own shocks at every horizon gets little predictive help from the others.
Use with care
The shares depend on the ordering of the series, like the impulse responses.
# Forecast error variance decomposition — Codesplash Chart Lab (recipe "fevd")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5) # stripes let the chart surface show through
df = pd.read_csv("fevd-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["forecast series"] = pd.Categorical(df["forecast series"].astype("string"), categories=["sales", "ad spend", "price"])
df["shock"] = pd.Categorical(df["shock"].astype("string"), categories=["sales", "ad spend", "price"])
_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")
H = "steps ahead"
V = "share"
R = "forecast series"
S = "shock"
responses = list(pd.unique(df[R]))
shocks = list(pd.unique(df[S]))
fig, axes = plt.subplots(1, len(responses), figsize=(8, 3.6), sharey=True, squeeze=False)
for ax, r in zip(axes[0], responses):
wide = df[df[R] == r].pivot(index=H, columns=S, values=V).reindex(columns=shocks).sort_index()
# each shock's layer also has its own texture, as in the app
ax.stackplot(wide.index, wide.T.to_numpy(), labels=shocks, colors=PALETTE[: len(shocks)], hatch=[SERIES_HATCHES[k % 8] for k in range(len(shocks))], hatchcolor=HATCH_INK, linewidth=0, alpha=0.8)
ax.set_title(str(r), fontsize=9)
ax.set_ylim(0, 1)
axes[0][0].set_ylabel("share of forecast error variance")
axes[0][0].legend(fontsize=8, loc="lower right")
fig.supxlabel("steps ahead", fontsize=9)
plt.show()Needs pandas, numpy, matplotlib · reads fevd-demo.csv · app theme from the optional codesplash helper
# Forecast error variance decomposition — Codesplash Chart Lab (recipe "fevd")
# 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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,0.5)" # stripes let the chart surface show through
df = pd.read_csv("fevd-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["forecast series"] = pd.Categorical(df["forecast series"].astype("string"), categories=["sales", "ad spend", "price"])
df["shock"] = pd.Categorical(df["shock"].astype("string"), categories=["sales", "ad spend", "price"])
_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
H = "steps ahead"
V = "share"
R = "forecast series"
S = "shock"
responses = list(pd.unique(df[R]))
shocks = list(pd.unique(df[S]))
fig = make_subplots(rows=1, cols=len(responses), shared_yaxes=True, subplot_titles=[str(r) for r in responses])
for j, r in enumerate(responses):
for k, s in enumerate(shocks):
d = df[(df[R] == r) & (df[S] == s)].sort_values(H)
fig.add_trace(go.Scatter(x=d[H], y=d[V], mode="lines", stackgroup=f"g{j}", name=str(s), legendgroup=str(s), showlegend=j == 0, line=dict(color=PALETTE[k % len(PALETTE)]),
fillpattern=dict(shape=SERIES_HATCHES[k % 8], fgcolor=HATCH_INK, fillmode="overlay")), row=1, col=j + 1) # texture per shock, as in the app
fig.update_yaxes(range=[0, 1])
fig.show()Needs pandas, numpy, plotly · reads fevd-demo.csv · app theme from the optional codesplash helper
# Forecast error variance decomposition — Codesplash Chart Lab (recipe "fevd")
# 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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("fevd-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["forecast series"]] <- factor(df[["forecast series"]], levels = c("sales", "ad spend", "price"))
df[["shock"]] <- factor(df[["shock"]], levels = c("sales", "ad spend", "price"))
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
H <- "steps ahead"
V <- "share"
R <- "forecast series"
S <- "shock"
d <- data.frame(h = df[[H]], v = df[[V]], response = df[[R]], shock = factor(df[[S]], levels = rev(unique(as.character(df[[S]])))))
p <- ggplot(d, aes(h, v, fill = shock)) +
geom_area(alpha = 0.8) +
facet_wrap(~ response) +
scale_fill_manual(values = rev(cs_textures(cs_cat[seq_along(levels(d$shock))]))) + # texture per shock, as in the app
labs(x = "steps ahead", y = "share of forecast error variance")
print(p)Needs ggplot2 · reads fevd-demo.csv · app theme from the optional codesplashr helper