svgschoenfeld
Schoenfeld residuals
Does a Cox model coefficient change over time (proportional-hazards check)?
How to read it
- Read one panel per model term.
- A flat smooth means the coefficient is stable over time: proportional hazards looks fine.
- A clear slope means the hazard ratio changes over time.
- Callout 1: A flat smooth: this coefficient is stable.
- Callout 2: A sloping smooth: this effect changes over time.
- Callout 3: The dashed zero line.
Watch out
- With many events, tiny slopes reach significance. Judge the size of the change.
Defaults
- Smooth
- On
- Which smooth to draw through the residuals.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
- Residuals are the engine's scaled Schoenfeld residuals (R `cox.zph`, transform "km" by default); the test statistics come from the engine.
- The smooth is LOESS (span 2/3, degree 1) for display; R draws a natural spline with 4 df.
- At most six terms are drawn.
# Schoenfeld residuals — Codesplash Chart Lab (recipe "schoenfeld")
# controls: smooth=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.nonparametric.smoothers_lowess import lowess
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("schoenfeld-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["term"] = pd.Categorical(df["term"].astype("string"), categories=["age", "treatment"])
_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)))
T = "KM-transformed time"
RES = "scaled Schoenfeld residual"
TERM = "term"
SMOOTH = True # lowess (f = 2/3, as R's lowess) estimate of β(t)
d = df.dropna(subset=[T, RES])
terms = levels_of(d[TERM]) if TERM else [None]
fig, axes = plt.subplots(1, len(terms), figsize=(4 * len(terms) + 1, 4), squeeze=False)
for ax, term in zip(axes[0], terms):
s = (d if term is None else d[d[TERM].astype(str) == str(term)]).sort_values(T)
ax.scatter(s[T], s[RES], s=10, color=GREY, edgecolors=REF, linewidths=0.3)
ax.axhline(0, color=REF, linestyle="--", linewidth=1)
if SMOOTH and len(s) > 3:
rng = float(s[T].max() - s[T].min())
fit = lowess(s[RES], s[T], frac=2 / 3, it=3, delta=0.01 * rng)
ax.plot(fit[:, 0], fit[:, 1], color=PALETTE[0], linewidth=2)
ax.set_title(str(term) if term is not None else RES, fontsize=10)
ax.set_xlabel(T)
axes[0][0].set_ylabel(RES)
fig.tight_layout()
plt.show()Needs pandas, numpy, matplotlib, statsmodels · reads schoenfeld-demo.csv · app theme from the optional codesplash helper
# Schoenfeld residuals — Codesplash Chart Lab (recipe "schoenfeld")
# controls: smooth=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from statsmodels.nonparametric.smoothers_lowess import lowess
from plotly.subplots import make_subplots
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("schoenfeld-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["term"] = pd.Categorical(df["term"].astype("string"), categories=["age", "treatment"])
_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)))
T = "KM-transformed time"
RES = "scaled Schoenfeld residual"
TERM = "term"
SMOOTH = True
d = df.dropna(subset=[T, RES])
terms = levels_of(d[TERM]) if TERM else [None]
fig = make_subplots(rows=1, cols=len(terms), subplot_titles=[str(t) if t is not None else RES for t in terms])
for k, term in enumerate(terms, start=1):
s = (d if term is None else d[d[TERM].astype(str) == str(term)]).sort_values(T)
fig.add_scatter(x=s[T], y=s[RES], mode="markers", marker=dict(color=GREY, size=5, line=dict(color=REF, width=0.5)), showlegend=False, row=1, col=k)
fig.add_hline(y=0, line=dict(color=REF, dash="dash", width=1), row=1, col=k)
if SMOOTH and len(s) > 3:
rng = float(s[T].max() - s[T].min())
fit = lowess(s[RES], s[T], frac=2 / 3, it=3, delta=0.01 * rng)
fig.add_scatter(x=fit[:, 0], y=fit[:, 1], mode="lines", line=dict(color=PALETTE[0], width=2), showlegend=False, row=1, col=k)
fig.update_xaxes(title_text=T, row=1, col=k)
fig.update_yaxes(title_text=RES, row=1, col=1)
fig.show()Needs pandas, numpy, plotly, statsmodels · reads schoenfeld-demo.csv · app theme from the optional codesplash helper
# Schoenfeld residuals — Codesplash Chart Lab (recipe "schoenfeld")
# controls: smooth=true
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("schoenfeld-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["term"]] <- factor(df[["term"]], levels = c("age", "treatment"))
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)]))
t_col <- "KM-transformed time"
res_col <- "scaled Schoenfeld residual"
term_col <- "term"
smooth <- TRUE # lowess (f = 2/3) estimate of beta(t)
d <- df[!is.na(df[[t_col]]) & !is.na(df[[res_col]]), ]
d <- data.frame(t = d[[t_col]], r = d[[res_col]], term = if (is.null(term_col)) res_col else factor(as.character(d[[term_col]]), levels = levels_of(d[[term_col]])))
fits <- do.call(rbind, lapply(split(d, d$term, drop = TRUE), function(s) { f <- stats::lowess(s$t, s$r); data.frame(term = s$term[1], t = f$x, r = f$y) }))
p <- ggplot(d, aes(t, r)) + geom_hline(yintercept = 0, linetype = "dashed", colour = ref_col) +
geom_point(shape = 21, fill = grey_col, colour = ref_col, size = 1.4, stroke = 0.2) +
{ if (smooth) geom_line(data = fits, colour = cs_cat[1], linewidth = 1) } +
facet_wrap(~term, scales = "free_y") + labs(x = t_col, y = res_col) + theme_cs
print(p)Needs ggplot2 · reads schoenfeld-demo.csv · app theme from the optional codesplashr helper