svgshap-waterfall
SHAP waterfall
Why did the model make this particular prediction?
How to read it
- Start at the left marker: the average prediction.
- Each bar pushes the prediction up or down, largest first.
- End at the final value: this row's prediction.
- Callout 1: Baseline: the model's average output.
- Callout 2: This feature pushes the prediction up most.
- Callout 3: This row's prediction.
Watch out
- It explains one row. Don't generalize one row's story to the whole model.
Defaults
- Base value E[f(x)]
- 0
- Where the waterfall starts: the model's average output.
- Range -1,000,000,000 to 1,000,000,000, step 0.01
- Prediction f(x) (0 = base + Σ contributions)
- 0
- Where the waterfall ends: the model's output for this row.
- Range -1,000,000,000 to 1,000,000,000, step 0.01
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.
- Steps keep the engine's order (usually |SHAP| descending with the remaining features summed into one row); the last bar ends at base + Σ contributions, which equals f(x) by SHAP's additivity.
- The run supplies the base value (expected model output over the background data) and, optionally, the prediction for the label.
# SHAP waterfall — Codesplash Chart Lab (recipe "shap-waterfall")
# controls: base=0, prediction=0
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("shap-waterfall-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["glucose", "BMI", "age", "pedigree", "pregnancies", "blood pressure", "4 other features"])
_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")
FEAT = "feature"
CON = "SHAP value (log-odds)"
V = "value"
BASE, PRED_SET = 0, 0 # E[f(x)]; f(x) when given (0 = base + Σ SHAP)
d = df.dropna(subset=[FEAT, CON]).reset_index(drop=True)
end = BASE + d[CON].cumsum()
start = end - d[CON]
pred = PRED_SET if PRED_SET != 0 else float(end.iloc[-1])
labels = [f"{f} = {v:g}" if isinstance(v, float) and pd.notna(v) else (f"{f} = {v}" if V and pd.notna(v) else str(f)) for f, v in zip(d[FEAT], d[V] if V else [None] * len(d))]
y = np.arange(len(d))[::-1] # first feature at the top
fig, ax = plt.subplots(figsize=(8, 0.42 * len(d) + 1.6))
cols = [DIV[0] if v > 0 else DIV[-1] for v in d[CON]] # raises the prediction: red; lowers it: blue
ax.barh(y, d[CON], left=start, color=cols, height=0.6)
for yi, s, e, v in zip(y, start, end, d[CON]):
ax.annotate(f"{v:+.3g}", (max(s, e), yi), xytext=(4, 0), textcoords="offset points", va="center", fontsize=8)
ax.axvline(BASE, color="grey", linestyle="--", linewidth=1)
ax.axvline(pred, color=REF, linewidth=1.2)
ax.set_yticks(y, labels)
ax.margins(x=0.1) # room for the value labels
ax.set_xlabel(f"E[f(x)] = {BASE:.3g}, f(x) = {pred:.3g}")
plt.show()Needs pandas, numpy, matplotlib · reads shap-waterfall-demo.csv · app theme from the optional codesplash helper
# SHAP waterfall — Codesplash Chart Lab (recipe "shap-waterfall")
# controls: base=0, prediction=0
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("shap-waterfall-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["glucose", "BMI", "age", "pedigree", "pregnancies", "blood pressure", "4 other features"])
_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")
FEAT = "feature"
CON = "SHAP value (log-odds)"
V = "value"
BASE, PRED_SET = 0, 0
d = df.dropna(subset=[FEAT, CON]).reset_index(drop=True)
labels = [f"{f} = {v:g}" if isinstance(v, float) and pd.notna(v) else (f"{f} = {v}" if V and pd.notna(v) else str(f)) for f, v in zip(d[FEAT], d[V] if V else [None] * len(d))]
pred = PRED_SET if PRED_SET != 0 else float(BASE + d[CON].sum())
fig = go.Figure(go.Waterfall(orientation="h", y=labels[::-1], x=list(d[CON])[::-1], base=BASE, measure=["relative"] * len(d),
increasing=dict(marker=dict(color=DIV[0])), decreasing=dict(marker=dict(color=DIV[-1])), connector=dict(line=dict(color="grey", width=0.5))))
fig.add_vline(x=BASE, line=dict(color="grey", dash="dash", width=1))
fig.add_vline(x=pred, line=dict(color=REF, width=1.2))
fig.update_layout(xaxis_title=f"E[f(x)] = {BASE:.3g}, f(x) = {pred:.3g}")
fig.show()Needs pandas, numpy, plotly · reads shap-waterfall-demo.csv · app theme from the optional codesplash helper
# SHAP waterfall — Codesplash Chart Lab (recipe "shap-waterfall")
# controls: base=0, prediction=0
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("shap-waterfall-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["feature"]] <- factor(df[["feature"]], levels = c("glucose", "BMI", "age", "pedigree", "pregnancies", "blood pressure", "4 other features"))
df[["value"]] <- factor(df[["value"]])
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
feat_col <- "feature"
con_col <- "SHAP value (log-odds)"
v_col <- "value"
base <- 0; pred_set <- 0 # E[f(x)]; f(x) when given (0 = base + sum of SHAP)
d <- df[!is.na(df[[feat_col]]) & !is.na(df[[con_col]]), ]
v <- if (is.null(v_col)) rep(NA, nrow(d)) else as.character(d[[v_col]])
d <- data.frame(lab = ifelse(is.na(v), as.character(d[[feat_col]]), paste(d[[feat_col]], "=", v)), con = d[[con_col]])
d$end <- base + cumsum(d$con); d$start <- d$end - d$con
d$row <- factor(seq_len(nrow(d)), levels = rev(seq_len(nrow(d)))) # first feature at the top
pred <- if (pred_set != 0) pred_set else d$end[nrow(d)]
p <- ggplot(d) + geom_rect(aes(xmin = start, xmax = end, ymin = as.numeric(row) - 0.3, ymax = as.numeric(row) + 0.3, fill = con > 0)) +
geom_text(aes(x = pmax(start, end), y = as.numeric(row), label = sprintf("%+.3g", con)), hjust = -0.15, size = 3) +
geom_vline(xintercept = base, linetype = "dashed", colour = "grey60") + geom_vline(xintercept = pred, colour = ref_col) +
scale_fill_manual(values = c("FALSE" = div_ramp[length(div_ramp)], "TRUE" = div_ramp[1]), guide = "none") +
scale_y_continuous(breaks = seq_len(nrow(d)), labels = rev(d$lab)) + scale_x_continuous(expand = expansion(mult = c(0.05, 0.14))) + # room for the value labels
labs(x = sprintf("E[f(x)] = %.3g, f(x) = %.3g", base, pred), y = NULL) + theme_cs
print(p)Needs ggplot2 · reads shap-waterfall-demo.csv · app theme from the optional codesplashr helper