Skip to content
svgkm-curve

Kaplan–Meier curve

What fraction survives (is event-free) over time, and do groups differ?

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

How to read it

  1. Read the height as the estimated share still event-free at that time.
  2. Read across at 50% to find each group's median time.
  3. Check the number at risk below: few at risk makes the right end unreliable.
  1. Callout 1: Dotted guide: the median survival time.
  2. Callout 2: A tick: a censored subject, not an event.
  3. Callout 3: Number at risk at each time.

Watch out

  • Flat tails with few at risk are not evidence that risk stopped.
  • Crossing curves break the proportional hazards idea that a single hazard ratio assumes.

Defaults

Confidence band
On
Shade the uncertainty around the curve.
Number-at-risk table
On
Show how many subjects remain at each time.
Censoring ticks
On
Mark subjects who left the study without the event.
Median guides
On
Draw guides down to each group's median time.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • One row per event or censoring time per group (R `summary(survfit, censored = TRUE)`), plus a start row at t = 0; the curve is right-continuous.
  • Number at risk at a tick t is the at-risk count of the first row at or after t (R `summary(fit, times = t, extend = TRUE)`); 0 beyond the last row.
  • The demo uses Greenwood variance with log-log intervals (R `conf.type = "log-log"`, the survival package's recommended transform).
  • Median guides drop from S = 0.5 at the first time the curve reaches 0.5 (the engine reports the exact median and its CI).
# Kaplan–Meier curve — Codesplash Chart Lab (recipe "km-curve")
# controls: ci=true, riskTable=true, censorTicks=true, median=true
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("km-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["standard", "new therapy"])

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 = "months"
SV = "survival"
LO = "lower"
HI = "upper"
S = "arm"
NR = "n.risk"
NC = "n.censor"
CI, RISK, TICKS, MEDIAN = True, True, True, True
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
    d = df if name is None else df[df[S].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values([T], kind="mergesort")))
show_risk = RISK and NR is not None
if show_risk:
    fig, (ax, axr) = plt.subplots(2, 1, figsize=(8, 5.6), sharex=True, gridspec_kw={"height_ratios": [4, 1]})
else:
    fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    if CI and LO and HI:
        ax.fill_between(d[T], d[LO], d[HI], step="post", color=col, alpha=0.15, lw=0)
    ax.step(d[T], d[SV], where="post", color=col, linewidth=2, label=name or SV)
    if TICKS and NC:
        cz = d[d[NC] > 0]
        ax.scatter(cz[T], cz[SV], marker="|", s=70, color=col, zorder=3)  # censored
    below = d[d[SV] <= 0.5]
    if MEDIAN and len(below):
        tm = below[T].iloc[0]  # median survival: first time S(t) ≤ 0.5
        ax.plot([0, tm, tm], [0.5, 0.5, 0], color=col, linestyle=":", linewidth=1)
ax.set_ylim(0, 1.02)
ax.set_ylabel(SV)
if S:
    ax.legend(fontsize=8)
if show_risk:
    tmax = max(float(d[T].max()) for _, d in series)
    ticks = [t for t in ax.get_xticks() if 0 <= t <= tmax]
    for i, (name, d) in enumerate(series):
        for t in ticks:
            nxt = d[(d[T] >= t) & d[NR].notna()]  # at risk at t: the risk set of the next time ≥ t
            axr.text(t, i, str(int(nxt[NR].iloc[0])) if len(nxt) else "0", ha="center", va="center", fontsize=8, color=PALETTE[i % len(PALETTE)])
    axr.set_yticks(range(len(series)), [n or "at risk" for n, _ in series])
    axr.set_ylim(len(series) - 0.5, -0.5)
    axr.set_xlim(ax.get_xlim())
    axr.tick_params(left=False)
    for side in axr.spines.values():
        side.set_visible(False)
    axr.set_xlabel(T)
else:
    ax.set_xlabel(T)
plt.show()

Needs pandas, numpy, matplotlib · reads km-curve-demo.csv · app theme from the optional codesplash helper