Skip to content
svgschoenfeld

Schoenfeld residuals

Does a Cox model coefficient change over time (proportional-hazards check)?

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

How to read it

  1. Read one panel per model term.
  2. A flat smooth means the coefficient is stable over time: proportional hazards looks fine.
  3. A clear slope means the hazard ratio changes over time.
  1. Callout 1: A flat smooth: this coefficient is stable.
  2. Callout 2: A sloping smooth: this effect changes over time.
  3. 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