svgshap-force
SHAP force plot
Which features pushed this one prediction up, and which pulled it down?
How to read it
- Start at the base value: the model's average output.
- Follow the contributions pushing up from one side and down from the other.
- 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
# SHAP force plot — Codesplash Chart Lab (recipe "shap-force")
# controls: base=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-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 = go.Figure()
at = pred
for _, r in d[d[CON] > 0].sort_values(CON, ascending=False).iterrows():
fig.add_bar(y=[""], x=[r[CON]], base=[at - r[CON]], orientation="h", marker_color=DIV[0], name=str(r[FEAT]), text=str(r[FEAT]))
at -= r[CON]
at = pred
for _, r in d[d[CON] < 0].sort_values(CON).iterrows():
fig.add_bar(y=[""], x=[-r[CON]], base=[at], orientation="h", marker_color=DIV[-1], name=str(r[FEAT]), text=str(r[FEAT]))
at -= r[CON]
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(barmode="overlay", showlegend=False, xaxis_title=f"E[f(x)] = {BASE:.3g}, f(x) = {pred:.3g}")
fig.show()Needs pandas, numpy, plotly · reads shap-force-demo.csv · app theme from the optional codesplash helper
# SHAP force plot — Codesplash Chart Lab (recipe "shap-force")
# controls: base=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-force-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"))
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)"
base <- 0 # E[f(x)]
d <- df[!is.na(df[[feat_col]]) & !is.na(df[[con_col]]), ]
con <- d[[con_col]]; feat <- as.character(d[[feat_col]])
pred <- base + sum(con) # f(x) = base + sum of SHAP
up <- order(-con); up <- up[con[up] > 0]; down <- order(con); down <- down[con[down] < 0]
seg <- rbind(
data.frame(feat = feat[up], start = pred - cumsum(con[up]), end = pred - cumsum(con[up]) + con[up], raises = rep(TRUE, length(up))),
data.frame(feat = feat[down], start = pred - cumsum(con[down]) + con[down], end = pred - cumsum(con[down]), raises = rep(FALSE, length(down)))
)
p <- ggplot(seg) + geom_rect(aes(xmin = start, xmax = end, ymin = -0.25, ymax = 0.25, fill = raises), colour = "white") +
geom_text(aes(x = (start + end) / 2, y = 0, label = feat), colour = "white", size = 2.6) +
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 = NULL, limits = c(-0.6, 0.6)) +
labs(x = sprintf("E[f(x)] = %.3g, f(x) = %.3g", base, pred), y = NULL) + theme_cs
print(p)Needs ggplot2 · reads shap-force-demo.csv · app theme from the optional codesplashr helper