svggam-partial
GAM partial effects
What does each feature add to an additive model's prediction?
How to read it
- Read each panel as one feature: how far it moves the prediction above or below average as its value changes.
- Check the shaded band, about two standard errors: where it covers the dashed zero line, the data can't tell the effect from none.
- Compare heights across panels. They share one y axis, so a taller curve is a larger effect.
- Callout 1: A steep stretch: the feature matters most here.
- Callout 2: Dashed line: the average prediction.
- Callout 3: The band widens at the edges, where there are fewer rows.
Watch out
- Effects are on the model's link scale: log-odds or log for binary, Poisson, Gamma and Tweedie models, not the original units.
- A partial effect describes this model holding the others fixed. With correlated features it isn't a causal effect.
Defaults
No settings: the chart draws one way.
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.
- Effects are centred on the training rows, on the link scale (response, log-odds or log). The band is ±2 standard errors of the smooth from the penalized fit's covariance. All panels share one y axis, so curve heights compare directly.
# GAM partial effects — Codesplash Chart Lab (recipe "gam-partial")
# controls: defaults
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("gam-partial-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=["Temperature", "Wind", "Solar radiation"])
_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")
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
F = "Feature"
X = "Value"
E = "Effect"
L = "Lower"
U = "Upper"
groups = levels_of(df[F]) if F else [None]
series = []
for name in groups:
d = df if name is None else df[df[F].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values([X], kind="mergesort")))
n = len(series)
cols = min(n, 3)
rows = int(np.ceil(n / cols))
fig, axes = plt.subplots(rows, cols, figsize=(3.4 * cols, 2.6 * rows), sharey=True, squeeze=False)
for ax in axes.flat[n:]:
ax.set_visible(False)
for ax, (name, d) in zip(axes.flat, series):
d = d.dropna(subset=[X, E]).sort_values(X)
ax.axhline(0, color=REF, linestyle="--", linewidth=1)
if L and U:
ax.fill_between(d[X], d[L], d[U], color=PALETTE[0], alpha=0.16, linewidth=0)
ax.plot(d[X], d[E], color=PALETTE[0], linewidth=2)
ax.set_title(name, fontsize=10, loc="left")
for ax in axes[:, 0]:
ax.set_ylabel(E)
fig.tight_layout()
plt.show()Needs pandas, numpy, matplotlib · reads gam-partial-demo.csv · app theme from the optional codesplash helper
# GAM partial effects — Codesplash Chart Lab (recipe "gam-partial")
# controls: defaults
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("gam-partial-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=["Temperature", "Wind", "Solar radiation"])
from plotly.subplots import make_subplots
_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")
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
F = "Feature"
X = "Value"
E = "Effect"
L = "Lower"
U = "Upper"
groups = levels_of(df[F]) if F else [None]
series = []
for name in groups:
d = df if name is None else df[df[F].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values([X], kind="mergesort")))
n = len(series)
cols = min(n, 3)
rows = int(np.ceil(n / cols))
fig = make_subplots(rows=rows, cols=cols, shared_yaxes=True, subplot_titles=[name for name, _ in series])
for k, (name, d) in enumerate(series):
d = d.dropna(subset=[X, E]).sort_values(X)
r, s = k // cols + 1, k % cols + 1
if L and U:
fig.add_trace(go.Scatter(x=d[X], y=d[U], mode="lines", line_width=0, showlegend=False), row=r, col=s)
fig.add_trace(go.Scatter(x=d[X], y=d[L], mode="lines", line_width=0, fill="tonexty", fillcolor="rgba(113,157,239,0.16)", showlegend=False), row=r, col=s)
fig.add_trace(go.Scatter(x=d[X], y=d[E], mode="lines", line_color=PALETTE[0], showlegend=False), row=r, col=s)
fig.add_hline(y=0, line_dash="dash", line_color=REF, row=r, col=s)
fig.update_layout(height=280 * rows)
fig.show()Needs pandas, numpy, plotly · reads gam-partial-demo.csv · app theme from the optional codesplash helper
# GAM partial effects — Codesplash Chart Lab (recipe "gam-partial")
# controls: defaults
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("gam-partial-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("Temperature", "Wind", "Solar radiation"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
F <- "Feature"
X <- "Value"
E <- "Effect"
L <- "Lower"
U <- "Upper"
d <- data.frame(feature = factor(as.character(df[[F]]), levels = levels_of(df[[F]])), x = df[[X]], effect = df[[E]])
if (!is.null(L) && !is.null(U)) {
d$lower <- df[[L]]
d$upper <- df[[U]]
}
d <- d[is.finite(d$x) & is.finite(d$effect), ]
p <- ggplot(d, aes(x, effect)) +
geom_hline(yintercept = 0, linetype = "dashed", colour = ref_col)
if ("lower" %in% names(d)) p <- p + geom_ribbon(aes(ymin = lower, ymax = upper), fill = cs_cat[[1]], alpha = 0.16)
p <- p + geom_line(colour = cs_cat[[1]], linewidth = 0.8) +
facet_wrap(~feature, scales = "free_x") +
labs(x = NULL, y = E) + theme_cs
print(p)Needs ggplot2 · reads gam-partial-demo.csv · app theme from the optional codesplashr helper