svgkm-curve
Kaplan–Meier curve
What fraction survives (is event-free) over time, and do groups differ?
How to read it
- Read the height as the estimated share still event-free at that time.
- Read across at 50% to find each group's median time.
- Check the number at risk below: few at risk makes the right end unreliable.
- Callout 1: Dotted guide: the median survival time.
- Callout 2: A tick: a censored subject, not an event.
- 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
# 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 plotly.express as px
import plotly.graph_objects as go
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("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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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
fig = make_subplots(rows=2 if show_risk else 1, cols=1, shared_xaxes=True, row_heights=[0.8, 0.2] if show_risk else None, vertical_spacing=0.06)
tmax = max(float(d[T].max()) for _, d in series)
ticks = np.linspace(0, tmax, 6)
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
if CI and LO and HI:
fig.add_scatter(x=d[T], y=d[LO], mode="lines", line=dict(width=0, shape="hv"), showlegend=False, hoverinfo="skip", row=1, col=1)
fig.add_scatter(x=d[T], y=d[HI], mode="lines", line=dict(width=0, shape="hv"), fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip", row=1, col=1)
fig.add_scatter(x=d[T], y=d[SV], mode="lines", name=name or SV, line=dict(color=col, width=2, shape="hv"), row=1, col=1)
if TICKS and NC:
cz = d[d[NC] > 0]
fig.add_scatter(x=cz[T], y=cz[SV], mode="markers", marker=dict(symbol="line-ns-open", size=9, color=col), showlegend=False, row=1, col=1)
below = d[d[SV] <= 0.5]
if MEDIAN and len(below):
tm = float(below[T].iloc[0])
fig.add_scatter(x=[0, tm, tm], y=[0.5, 0.5, 0], mode="lines", line=dict(color=col, dash="dot", width=1), showlegend=False, row=1, col=1)
if show_risk:
counts = []
for t in ticks:
nxt = d[(d[T] >= t) & d[NR].notna()]
counts.append(str(int(nxt[NR].iloc[0])) if len(nxt) else "0")
fig.add_scatter(x=ticks, y=[name or "at risk"] * len(ticks), mode="text", text=counts, textfont=dict(color=col, size=11), showlegend=False, row=2, col=1)
fig.update_yaxes(range=[0, 1.02], title=SV, row=1, col=1)
fig.update_xaxes(title=T, row=2 if show_risk else 1, col=1)
fig.show()Needs pandas, numpy, plotly · reads km-curve-demo.csv · app theme from the optional codesplash helper
# Kaplan–Meier curve — Codesplash Chart Lab (recipe "km-curve")
# controls: ci=true, riskTable=true, censorTicks=true, median=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("km-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("standard", "new therapy"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
arrange <- function(plots, layout, widths = NULL, heights = NULL) {
# layout: matrix of plot indices (NA = empty cell). patchwork aligns the panels when it is
# installed; otherwise base grid viewports place the plots (axes may not line up exactly).
widths <- if (is.null(widths)) rep(1, ncol(layout)) else widths
heights <- if (is.null(heights)) rep(1, nrow(layout)) else heights
if (requireNamespace("patchwork", quietly = TRUE)) {
design <- paste(apply(layout, 1, function(r) paste(ifelse(is.na(r), "#", LETTERS[r]), collapse = "")), collapse = "\n")
print(patchwork::wrap_plots(plots, design = design, widths = widths, heights = heights, guides = "collect"))
return(invisible())
}
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout),
widths = grid::unit(widths, "null"), heights = grid::unit(heights, "null"))))
for (i in seq_along(plots)) {
at <- which(layout == i, arr.ind = TRUE)
print(plots[[i]], vp = grid::viewport(layout.pos.row = unique(at[, 1]), layout.pos.col = unique(at[, 2])))
}
}
t_col <- "months"
s_col <- "survival"
lo_col <- "lower"
hi_col <- "upper"
g_col <- "arm"
nr_col <- "n.risk"
nc_col <- "n.censor"
show_ci <- TRUE; censor_ticks <- TRUE; show_median <- TRUE
d <- data.frame(t = df[[t_col]], s = df[[s_col]], g = if (is.null(g_col)) "" else factor(as.character(df[[g_col]]), levels = levels_of(df[[g_col]])))
d$lo <- if (is.null(lo_col)) NA_real_ else df[[lo_col]]
d$hi <- if (is.null(hi_col)) NA_real_ else df[[hi_col]]
d$nr <- if (is.null(nr_col)) NA_real_ else df[[nr_col]]
d$nc <- if (is.null(nc_col)) 0 else df[[nc_col]]
d <- d[!is.na(d$t) & !is.na(d$s), ]
d <- d[order(d$g, d$t), ]
d$t_end <- stats::ave(d$t, d$g, FUN = function(v) c(v[-1], v[length(v)])) # step to the next time
med <- do.call(rbind, lapply(split(d, d$g, drop = TRUE), function(s) { b <- s[s$s <= 0.5, ]; if (nrow(b)) data.frame(g = s$g[1], tm = b$t[1]) else NULL }))
p <- ggplot(d, aes(t, s, colour = g, fill = g)) +
{ if (show_ci && !all(is.na(d$lo))) geom_rect(aes(xmin = t, xmax = t_end, ymin = lo, ymax = hi), colour = NA, alpha = 0.15) } +
geom_step(linewidth = 0.9) +
{ if (censor_ticks) geom_point(data = d[d$nc > 0, ], shape = 3, size = 2) } +
{ if (show_median && !is.null(med)) geom_segment(data = med, aes(x = 0, xend = tm, y = 0.5, yend = 0.5, colour = g), inherit.aes = FALSE, linetype = "dotted") } +
{ if (show_median && !is.null(med)) geom_segment(data = med, aes(x = tm, xend = tm, y = 0.5, yend = 0, colour = g), inherit.aes = FALSE, linetype = "dotted") } +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") + scale_fill_manual(values = cs_cat, guide = "none") +
coord_cartesian(ylim = c(0, 1.02)) + labs(x = t_col, y = s_col, colour = NULL) + theme_cs
ticks <- pretty(c(0, max(d$t)))
ticks <- ticks[ticks <= max(d$t)]
at_risk <- do.call(rbind, lapply(split(d, d$g, drop = TRUE), function(s) data.frame(g = s$g[1], t = ticks,
n = vapply(ticks, function(tt) { nxt <- s[s$t >= tt & !is.na(s$nr), ]; if (nrow(nxt)) nxt$nr[1] else 0 }, numeric(1))))) # risk set of the next time ≥ t
tab <- ggplot(at_risk, aes(t, g, label = n, colour = g)) + geom_text(size = 3) +
scale_colour_manual(values = cs_cat, guide = "none") + scale_y_discrete(limits = rev) +
coord_cartesian(xlim = range(d$t)) + labs(x = t_col, y = NULL) + theme_cs
arrange(list(p + labs(x = NULL), tab), layout = matrix(1:2, ncol = 1), heights = c(4, 1))Needs ggplot2 · reads km-curve-demo.csv · app theme from the optional codesplashr helper