Skip to content
svgshap-waterfall

SHAP waterfall

Why did the model make this particular prediction?

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

How to read it

  1. Start at the left marker: the average prediction.
  2. Each bar pushes the prediction up or down, largest first.
  3. End at the final value: this row's prediction.
  1. Callout 1: Baseline: the model's average output.
  2. Callout 2: This feature pushes the prediction up most.
  3. 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