svgrmst-area
Restricted mean survival area
How much event-free time does each group have up to a horizon?
How to read it
- Read each curve as the share still event-free over time, and τ as the horizon marked by the dashed line.
- Read the area under a curve up to τ as that group's restricted mean survival time, given in the legend.
- Read the shaded gap between the curves as the difference in mean event-free time up to τ.
- Callout 1: τ: the area stops here.
- Callout 2: The shared area: time both groups have on average.
- Callout 3: The gap: extra event-free time for one group.
- Callout 4: Each group's restricted mean, in time units.
Watch out
- Choose τ from the question before you see the curves. It should also stay within the follow-up of both groups.
Defaults
- Horizon τ
- 0
- Time horizon for the area (0 uses the shorter follow-up).
- Range 0 to 1,000,000, step 10
Pinned in the code
- RMST = ∫₀^τ S(t) dt under the Kaplan–Meier step curve; the default τ is the shorter of the groups' last times.
# Restricted mean survival area — Codesplash Chart Lab (recipe "rmst-area")
# controls: tau=0
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("rmst-area-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=["control", "treated"])
_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")
T = "days"
Y = "survival"
G = "arm"
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)))
TAU = 0
groups = levels_of(df[G]) if G else [None]
curves = []
for g in groups:
d = df if g is None else df[df[G].astype(str) == str(g)]
d = d.dropna(subset=[T, Y]).sort_values(T, kind="stable")
curves.append(("all" if g is None else str(g), d[T].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)))
tau = TAU if TAU > 0 else min(t[-1] for _, t, _ in curves) # the shorter follow-up
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, t, s) in enumerate(curves):
keep = t <= tau
tt, ss = np.append(t[keep], tau), np.append(s[keep], s[keep][-1])
rmst = float(np.sum(np.diff(tt) * ss[:-1])) # area under the step curve
color = PALETTE[i % len(PALETTE)]
ax.step(tt, ss, where="post", color=color, label=f"{name}: RMST {rmst:.4g}")
ax.fill_between(tt, ss, step="post", color=color, alpha=0.12)
ax.axvline(tau, color=REF, linestyle="--")
ax.set_xlabel(T)
ax.set_ylabel("Survival probability")
ax.set_title(f"Restricted mean survival up to {tau:g}", fontsize=10, loc="left")
ax.legend(frameon=False)
plt.show()Needs pandas, numpy, matplotlib · reads rmst-area-demo.csv · app theme from the optional codesplash helper
# Restricted mean survival area — Codesplash Chart Lab (recipe "rmst-area")
# controls: tau=0
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("rmst-area-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=["control", "treated"])
_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")
T = "days"
Y = "survival"
G = "arm"
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)))
TAU = 0
groups = levels_of(df[G]) if G else [None]
curves = []
for g in groups:
d = df if g is None else df[df[G].astype(str) == str(g)]
d = d.dropna(subset=[T, Y]).sort_values(T, kind="stable")
curves.append(("all" if g is None else str(g), d[T].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)))
tau = TAU if TAU > 0 else min(t[-1] for _, t, _ in curves)
fig = go.Figure()
for i, (name, t, s) in enumerate(curves):
keep = t <= tau
tt, ss = np.append(t[keep], tau), np.append(s[keep], s[keep][-1])
rmst = float(np.sum(np.diff(tt) * ss[:-1]))
fig.add_scatter(x=tt, y=ss, mode="lines", name=f"{name}: RMST {rmst:.4g}", fill="tozeroy", line=dict(color=PALETTE[i % len(PALETTE)], shape="hv"))
fig.add_vline(x=tau, line_dash="dash", line_color=REF)
fig.update_layout(title=f"Restricted mean survival up to {tau:g}", xaxis_title=T, yaxis_title="Survival probability")
fig.show()Needs pandas, numpy, plotly · reads rmst-area-demo.csv · app theme from the optional codesplash helper
# Restricted mean survival area — Codesplash Chart Lab (recipe "rmst-area")
# controls: tau=0
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("rmst-area-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("control", "treated"))
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
t_col <- "days"
y_col <- "survival"
g_col <- "arm"
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
TAU <- 0
grp <- if (is.null(g_col)) rep("all", nrow(df)) else as.character(df[[g_col]])
lv <- if (is.null(g_col)) "all" else levels_of(df[[g_col]])
tau <- if (TAU > 0) TAU else min(vapply(lv, function(g) max(df[[t_col]][grp == g], na.rm = TRUE), numeric(1))) # the shorter follow-up
pd <- do.call(rbind, lapply(lv, function(g) {
d <- df[grp == g & df[[t_col]] <= tau, , drop = FALSE]
d <- d[order(d[[t_col]]), , drop = FALSE]
tt <- c(d[[t_col]], tau)
ss <- c(d[[y_col]], d[[y_col]][nrow(d)])
rmst <- sum(diff(tt) * ss[-length(ss)]) # area under the step curve
data.frame(t = tt, s = ss, g = factor(sprintf("%s: RMST %.4g", g, rmst)))
}))
p <- ggplot(pd, aes(t, s, colour = g)) + geom_step() + geom_vline(xintercept = tau, colour = ref_col, linetype = "dashed") +
scale_colour_manual(values = cs_cat, name = NULL) +
labs(x = t_col, y = "Survival probability", title = sprintf("Restricted mean survival up to %g", tau)) + theme_cs
print(p)Needs ggplot2 · reads rmst-area-demo.csv · app theme from the optional codesplashr helper