Skip to content
svgshap-force

SHAP force plot

Which features pushed this one prediction up, and which pulled it down?

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

How to read it

  1. Start at the base value: the model's average output.
  2. Follow the contributions pushing up from one side and down from the other.
  3. They meet at f(x): this row's prediction.

Watch out

  • It explains one prediction of the model, not what would happen if you changed the feature.

Defaults

Base value E[f(x)]
0
The model's average output over the background rows: where the explanation starts.
Range -1,000,000,000 to 1,000,000,000, step 0.01

Pinned in the code

  • Draws the explanation the Python or R engine computed; the chart computes nothing statistical.
  • The largest contribution sits next to f(x) on each side. f(x) = base + Σ contributions, by SHAP's additivity.
  • Red raises the prediction and blue lowers it, the usual SHAP convention.
# SHAP force plot — Codesplash Chart Lab (recipe "shap-force")
# controls: base=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-force-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"])

_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)"
BASE = 0  # E[f(x)]
d = df.dropna(subset=[FEAT, CON])
pred = BASE + d[CON].sum()  # f(x) = base + sum of SHAP
fig, ax = plt.subplots(figsize=(8, 2.4))
at = pred
for _, r in d[d[CON] > 0].sort_values(CON, ascending=False).iterrows():  # raises it: red, stacked up to f(x)
    ax.barh(0, r[CON], left=at - r[CON], height=0.5, color=DIV[0], edgecolor="white")
    ax.text(at - r[CON] / 2, 0, str(r[FEAT]), ha="center", va="center", fontsize=8, color="white", clip_on=True)
    at -= r[CON]
at = pred
for _, r in d[d[CON] < 0].sort_values(CON).iterrows():  # lowers it: blue, stacked down from f(x)
    ax.barh(0, -r[CON], left=at, height=0.5, color=DIV[-1], edgecolor="white")
    ax.text(at - r[CON] / 2, 0, str(r[FEAT]), ha="center", va="center", fontsize=8, color="white", clip_on=True)
    at -= r[CON]
ax.axvline(BASE, color="grey", linestyle="--", linewidth=1)
ax.axvline(pred, color=REF, linewidth=1.2)
ax.set_yticks([])
ax.set_xlabel(f"E[f(x)] = {BASE:.3g},  f(x) = {pred:.3g}")
plt.show()

Needs pandas, numpy, matplotlib · reads shap-force-demo.csv · app theme from the optional codesplash helper