svgshap-beeswarm
SHAP beeswarm
How does each feature push individual predictions up or down, and for which values?
How to read it
- Read each row as a feature, ranked by average impact.
- Read a dot's position: to the right pushes the prediction up.
- Read colour as the feature's value: red right and blue left means high values raise predictions.
- Callout 1: Top row: the feature with the largest average impact.
- Callout 2: Red on the right: high values push predictions up.
- Callout 3: Colour scale: the feature's value.
Watch out
- SHAP explains the model, not the world: it says what the model does, not what would happen if you changed the feature.
Defaults
- Features shown
- 20
- How many features to show, largest first.
- Range 3 to 40, step 1
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.
- Features are ordered by mean |SHAP| (global importance); within a feature, dots stack outward from the centre line in bins of one dot width so dense regions show their mass.
- Colour is the feature value scaled to [0, 1] by the engine (blue = low, red = high, as in the shap library); missing values are grey. Categorical features arrive one-hot, so 1 = that category.
- SHAP values explain the model's output scale (log-odds for boosted classifiers unless the run says probability).
# SHAP beeswarm — Codesplash Chart Lab (recipe "shap-beeswarm")
# controls: top=20
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
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-beeswarm-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"
SHAP = "SHAP value (log-odds)"
V = "feature value (rank-scaled)"
TOP = 20
d = df.dropna(subset=[FEAT, SHAP]).copy()
d[FEAT] = d[FEAT].astype(str)
order = d.assign(a=d[SHAP].abs()).groupby(FEAT)["a"].mean().sort_values(ascending=False).head(TOP).index.tolist() # by mean |SHAP|
ypos = {f: len(order) - 1 - i for i, f in enumerate(order)}
d = d[d[FEAT].isin(order)]
rng = np.random.default_rng(1) # vertical jitter stands in for the beeswarm layout
y = d[FEAT].map(ypos) + rng.uniform(-0.32, 0.32, len(d))
cmap = LinearSegmentedColormap.from_list("shap", [DIV[-1], DIV[0]]) # low value blue → high red
fig, ax = plt.subplots(figsize=(8, 0.42 * len(order) + 1.4))
ax.axvline(0, color="grey", linewidth=0.8)
sc = ax.scatter(d[SHAP], y, c=d[V] if V else None, cmap=cmap, s=7, alpha=0.8)
ax.set_yticks([ypos[f] for f in order], order)
ax.set_xlabel(SHAP)
if V:
fig.colorbar(sc, ax=ax, label=V)
plt.show()Needs pandas, numpy, matplotlib · reads shap-beeswarm-demo.csv · app theme from the optional codesplash helper
# SHAP beeswarm — Codesplash Chart Lab (recipe "shap-beeswarm")
# controls: top=20
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-beeswarm-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"
SHAP = "SHAP value (log-odds)"
V = "feature value (rank-scaled)"
TOP = 20
d = df.dropna(subset=[FEAT, SHAP]).copy()
d[FEAT] = d[FEAT].astype(str)
order = d.assign(a=d[SHAP].abs()).groupby(FEAT)["a"].mean().sort_values(ascending=False).head(TOP).index.tolist()
ypos = {f: len(order) - 1 - i for i, f in enumerate(order)}
d = d[d[FEAT].isin(order)]
rng = np.random.default_rng(1)
y = d[FEAT].map(ypos) + rng.uniform(-0.32, 0.32, len(d))
marker = dict(size=4, opacity=0.8, color=d[V], colorscale=[[0, DIV[-1]], [1, DIV[0]]], colorbar=dict(title=V)) if V else dict(size=4, color=PALETTE[0])
fig = go.Figure(go.Scattergl(x=d[SHAP], y=y, mode="markers", marker=marker, text=d[FEAT]))
fig.add_vline(x=0, line=dict(color="grey", width=1))
fig.update_yaxes(tickvals=[ypos[f] for f in order], ticktext=order)
fig.update_layout(xaxis_title=SHAP)
fig.show()Needs pandas, numpy, plotly · reads shap-beeswarm-demo.csv · app theme from the optional codesplash helper
# SHAP beeswarm — Codesplash Chart Lab (recipe "shap-beeswarm")
# controls: top=20
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-beeswarm-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"))
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"
shap_col <- "SHAP value (log-odds)"
v_col <- "feature value (rank-scaled)"
top_n <- 20
d <- df[!is.na(df[[feat_col]]) & !is.na(df[[shap_col]]), ]
d <- data.frame(f = as.character(d[[feat_col]]), s = d[[shap_col]], v = if (is.null(v_col)) NA_real_ else d[[v_col]])
rank <- sort(tapply(abs(d$s), d$f, mean), decreasing = TRUE) # by mean |SHAP|
keep <- head(names(rank), top_n)
d <- d[d$f %in% keep, ]
d$f <- factor(d$f, levels = rev(keep))
p <- ggplot(d, aes(s, f, colour = v)) + geom_vline(xintercept = 0, colour = "grey60") +
geom_point(position = position_jitter(width = 0, height = 0.3, seed = 1), size = 0.8, alpha = 0.8) + # jitter stands in for the beeswarm
scale_colour_gradient(low = div_ramp[length(div_ramp)], high = div_ramp[1], na.value = cs_cat[1]) +
labs(x = shap_col, y = NULL, colour = v_col) + theme_cs
print(p)Needs ggplot2 · reads shap-beeswarm-demo.csv · app theme from the optional codesplashr helper