svgcif-curve
Cumulative incidence (competing risks)
How likely is each type of event by a given time when other events compete?
How to read it
- Read the height as the chance this event has happened by that time.
- Compare causes: when other events compete, each curve stays below what a one-minus-survival curve would give.
- Read the two curves' sum as the chance of any event.
- Callout 1: The cumulative chance of this event.
- Callout 2: A competing event.
- Callout 3: Time from the start.
Watch out
- 1 − Kaplan–Meier overstates risk when other events compete. Use this chart instead.
Defaults
- Confidence band
- On
- Shade the uncertainty around the curve.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
- Cumulative incidence, not 1 − Kaplan–Meier: with competing risks 1 − KM overstates the probability of the event of interest.
- Demo: Aalen–Johansen CIFₖ(t) = Σ S(tⱼ−) dₖⱼ / nⱼ with S the all-cause Kaplan–Meier (R multi-state `survfit`).
# Cumulative incidence (competing risks) — Codesplash Chart Lab (recipe "cif-curve")
# controls: ci=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("cif-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["cause"] = pd.Categorical(df["cause"].astype("string"), categories=["relapse", "death without relapse"])
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)))
X = "months"
Y = "cumulative incidence"
LO = None
HI = None
G = "cause"
CI = True
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
d = df if name is None else df[df[G].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values([X], kind="mergesort")))
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[X], d[LO], d[HI], step="post", color=col, alpha=0.15, lw=0)
ax.step(d[X], d[Y], where="post", color=col, linewidth=2, label=name or Y)
ax.set_ylim(0, None)
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G:
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads cif-curve-demo.csv · app theme from the optional codesplash helper
# Cumulative incidence (competing risks) — Codesplash Chart Lab (recipe "cif-curve")
# controls: ci=true
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("cif-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["cause"] = pd.Categorical(df["cause"].astype("string"), categories=["relapse", "death without relapse"])
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})"
X = "months"
Y = "cumulative incidence"
LO = None
HI = None
G = "cause"
CI = True
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
d = df if name is None else df[df[G].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values([X], kind="mergesort")))
fig = go.Figure()
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
if CI and LO and HI:
fig.add_scatter(x=d[X], y=d[LO], mode="lines", line=dict(width=0, shape="hv"), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[HI], mode="lines", line=dict(width=0, shape="hv"), fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[Y], mode="lines", name=name or Y, line=dict(color=col, width=2, shape="hv"))
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()Needs pandas, numpy, plotly · reads cif-curve-demo.csv · app theme from the optional codesplash helper
# Cumulative incidence (competing risks) — Codesplash Chart Lab (recipe "cif-curve")
# controls: ci=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("cif-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["cause"]] <- factor(df[["cause"]], levels = c("relapse", "death without relapse"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "months"
y_col <- "cumulative incidence"
lo_col <- NULL
hi_col <- NULL
g_col <- "cause"
show_ci <- TRUE
d <- data.frame(x = df[[x_col]], y = df[[y_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 <- d[!is.na(d$x) & !is.na(d$y), ]
d <- d[order(d$g, d$x), ]
d$x_end <- stats::ave(d$x, d$g, FUN = function(v) c(v[-1], v[length(v)]))
p <- ggplot(d, aes(x, y, colour = g, fill = g)) +
{ if (show_ci && !all(is.na(d$lo))) geom_rect(aes(xmin = x, xmax = x_end, ymin = lo, ymax = hi), colour = NA, alpha = 0.15) } +
geom_step(linewidth = 0.9) +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") + scale_fill_manual(values = cs_cat, guide = "none") +
expand_limits(y = 0) + labs(x = x_col, y = y_col, colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads cif-curve-demo.csv · app theme from the optional codesplashr helper