Plot guides › Chart types

Kaplan-Meier survival curve

A Kaplan-Meier curve estimates the probability of surviving (or not having an event) past each time point, dropping at every event and marking censored subjects with ticks.

Example kaplan-meier survival curve made with matplotlib
Rendered from the code below, with example data.

When to use it

Ask for it in pltchat

Upload your file and type something like:

"Kaplan-Meier curve per treatment arm with censor ticks"

pltchat writes the loader and the plot for your columns, runs it in your browser and shows you the code.

The matplotlib code

Self-contained with example data; swap in pd.read_csv(...) or pd.read_excel(...) for your own file.

import numpy as np
import matplotlib.pyplot as plt

def kaplan_meier(time, event):
    order = np.argsort(time)
    time, event = time[order], event[order]
    t_out, s_out, s = [0.0], [1.0], 1.0
    for t in np.unique(time[event == 1]):
        at_risk = (time >= t).sum()
        deaths = ((time == t) & (event == 1)).sum()
        s *= 1 - deaths / at_risk
        t_out.append(t)
        s_out.append(s)
    return np.array(t_out), np.array(s_out)

rng = np.random.default_rng(20)
fig, ax = plt.subplots(figsize=(6.4, 4))
for arm, scale in [("Placebo", 14), ("Treatment", 24)]:
    t_event = rng.exponential(scale, 60)
    t_cens = rng.uniform(5, 40, 60)
    time = np.minimum(t_event, t_cens)
    event = (t_event <= t_cens).astype(int)
    t, s = kaplan_meier(time, event)
    line, = ax.step(t, s, where="post", label=arm)
    cens = time[event == 0]
    idx = np.searchsorted(t, cens, side="right") - 1
    ax.plot(cens, s[idx], "|", color=line.get_color(), ms=8)
ax.set_xlabel("Months")
ax.set_ylabel("Survival probability")
ax.set_ylim(0, 1.02)
ax.legend()
plt.tight_layout()
plt.show()

Make this with your data

Upload a CSV, Excel, JSON or Parquet file. Your first plot is always free.

Related plots