Kaplan-Meier & Log-rank
Survival analysis studies the time until an event: death, relapse, or any other endpoint that each patient reaches at most once. Its defining feature is censoring. Some patients are still event-free when the study stops, so you know that they lasted at least that long and nothing more. Dropping them biases the answer, and so does treating their last visit as an event.
The Kaplan-Meier estimator uses every patient for as long as that patient was observed. This page estimates the survival curves of two trial arms, then takes from them the summaries that a trial report needs: the median, the survival at a fixed time, the hazard ratio, the median follow-up, and the restricted mean survival time.
When to use Kaplan-Meier
Section titled “When to use Kaplan-Meier”Use it when the outcome is the time to one kind of event and some times are censored. It estimates the survival curve without assuming a distribution for the times, and the log-rank test compares the curves of two or more groups. When a second kind of event can prevent the first, such as death before relapse, use the methods of the competing risks page instead.
Get the data
Section titled “Get the data”Download survival.csv into your working directory. The invented table holds 120 patients in a two-arm trial, one row per patient, with three columns: group is control or treated, time is the follow-up in months, and event is 1 for a death and 0 for a censored time.
The times come from a simulation with known answers. The hazard is constant at 0.10 per month in the control arm and 0.05 per month in the treated arm, so the true medians are 6.9 and 13.9 months and the true hazard ratio is 0.5. The data cutoff falls 30 months after each patient starts, so every censored patient has a time of exactly 30.
The first block fits one curve per arm and prints the median survival with its 95% interval.
library(survival)library(ggplot2)library(ggsurvfit)library(survRM2)
df <- read.csv("survival.csv")dir.create("outputs", showWarnings = FALSE)
fit <- survfit(Surv(time, event) ~ group, data = df, conf.type = "log-log")print(fit)Call: survfit(formula = Surv(time, event) ~ group, data = df, conf.type = "log-log")
n events median 0.95LCL 0.95UCLgroup=control 60 58 5.38 3.43 8.81group=treated 60 52 10.97 7.47 16.12from pathlib import Path
import matplotlib.pyplot as pltimport pandas as pdfrom lifelines import CoxPHFitterfrom lifelines import KaplanMeierFitterfrom lifelines.plotting import add_at_risk_countsfrom lifelines.statistics import logrank_testfrom lifelines.utils import median_survival_timesfrom lifelines.utils import restricted_mean_survival_time
df = pd.read_csv("survival.csv")output = Path("outputs")output.mkdir(exist_ok=True)
arms = ["control", "treated"]fits = {}for arm in arms: rows = df[df["group"] == arm] fits[arm] = KaplanMeierFitter(label=arm).fit(rows["time"], rows["event"]) limits = median_survival_times(fits[arm].confidence_interval_) print(f"{arm}: n = {len(rows)}, events = {rows['event'].sum()}, " f"median = {fits[arm].median_survival_time_:.2f}, " f"95% CI {limits.iloc[0, 0]:.2f} to {limits.iloc[0, 1]:.2f}")control: n = 60, events = 58, median = 5.47, 95% CI 3.43 to 8.81treated: n = 60, events = 52, median = 11.26, 95% CI 7.47 to 16.12Half of the control arm has died by about 5.4 months and half of the treated arm by about 11 months. Both intervals are wide, 3.43 to 8.81 months and 7.47 to 16.12 months, and each contains the true median of its arm.
The interval limits agree between the tabs because the R call sets conf.type = "log-log". R’s default is "log". lifelines offers the log-log interval only, which its documentation calls the exponential Greenwood formula. The two transformations give different limits from the same curve, so name the one you used.
Why the two medians differ
Section titled “Why the two medians differ”The medians do not agree: R prints 5.38 and 10.97, lifelines 5.47 and 11.26. The curves are identical, so the difference comes from how each tool reads the median from a step function. The next block prints the steps of each curve near 0.5.
steps <- summary(fit)near_half <- steps$surv > 0.46 & steps$surv < 0.52cat(sprintf("%-8s t = %5.2f at risk = %2d S(t) = %.17f\n", sub("group=", "", steps$strata[near_half]), steps$time[near_half], steps$n.risk[near_half], steps$surv[near_half]), sep = "")print(quantile(fit, 0.5)$quantile)control t = 4.38 at risk = 32 S(t) = 0.51666666666666650control t = 5.28 at risk = 31 S(t) = 0.49999999999999983control t = 5.47 at risk = 30 S(t) = 0.46666666666666651treated t = 10.51 at risk = 32 S(t) = 0.51666666666666650treated t = 10.69 at risk = 31 S(t) = 0.49999999999999983treated t = 11.26 at risk = 30 S(t) = 0.48333333333333317treated t = 11.48 at risk = 29 S(t) = 0.46666666666666651 50group=control 5.375group=treated 10.975for arm in arms: curve = fits[arm].survival_function_[arm] near_half = curve[(curve > 0.46) & (curve < 0.52)] for time, survival in near_half.items(): print(f"{arm:<8} t = {time:5.2f} S(t) = {survival:.17f}")control t = 4.38 S(t) = 0.51666666666666683control t = 5.28 S(t) = 0.50000000000000022control t = 5.47 S(t) = 0.46666666666666673treated t = 10.51 S(t) = 0.51666666666666683treated t = 10.69 S(t) = 0.50000000000000022treated t = 11.26 S(t) = 0.48333333333333350treated t = 11.48 S(t) = 0.46666666666666673In the control arm, the 30th of 60 patients dies at 5.28 months and nobody is censored before that, so the estimate there is 30/60, exactly one half. The curve then stays at one half until the next death at 5.47 months. Every time from 5.28 to 5.47 months satisfies the definition of a median.
R returns the midpoint of that flat step, (5.28 + 5.47) / 2 = 5.375, which it prints as 5.38. Its stored value is 0.49999999999999983 and not 0.5, because the estimate is a running product of fractions, and quantile() treats a value within a small tolerance of 0.5 as equal to it. lifelines returns the first time at which the stored curve is at or below 0.5. Its running product comes out at 0.50000000000000022, a rounding error above one half, so it passes over 5.28 and returns the next event time, 5.47. The treated arm repeats the pattern at 10.69 and 11.26 months.
Three numbers are therefore defensible for the control median: 5.28, 5.38, and 5.47 months. The spread is a fifth of a month against an interval that is more than five months wide, so it changes no conclusion, but it explains why a table from one tool does not match a table from the other. This happens only when a step lands exactly on 0.5. The usual case is an arm with an even number of patients and no censoring before the median.
The survival curves
Section titled “The survival curves”The Kaplan-Meier curve is a staircase. It steps down at each death and stays flat between deaths. The shaded band is the pointwise 95% interval, and the table under the axis counts the patients still at risk at each tick.
km_plot <- survfit2(Surv(time, event) ~ group, data = df, conf.type = "log-log") |> ggsurvfit(linewidth = 0.8) + add_confidence_interval() + add_risktable(risktable_stats = "n.risk") + scale_x_continuous(breaks = seq(0, 30, 6)) + scale_color_manual(values = c("#e07a5f", "#1f4e5f")) + scale_fill_manual(values = c("#e07a5f", "#1f4e5f")) + labs(x = "Time (months)", y = "Survival probability")ggsave("outputs/km-r.png", km_plot, width = 6.5, height = 5, dpi = 150)
colors = {"control": "#e07a5f", "treated": "#1f4e5f"}fig, ax = plt.subplots(figsize=(6.5, 5))for arm in arms: fits[arm].plot_survival_function(ax=ax, color=colors[arm])ax.set_xticks(range(0, 31, 6))ax.set_xlabel("Time (months)")ax.set_ylabel("Survival probability")add_at_risk_counts(fits["control"], fits["treated"], ax=ax, rows_to_show=["At risk"])fig.tight_layout()fig.savefig(output / "km-python.png", dpi=150)plt.close(fig)
Read the at-risk row before you read the right side of a curve. At 24 months, 6 control patients and 13 treated patients remain, so one death moves the control curve by a sixth of its height. The bands show the same weakness: late in follow-up they span most of the distance between the two curves.
The two tables differ in the last column. ggsurvfit prints 2 and 8 at 30 months, the patients who were still in follow-up when the cutoff arrived. lifelines prints 0, because it counts the patients who remain after the censoring at that time. The tables agree at every tick where no patient leaves.
Survival at a fixed time
Section titled “Survival at a fixed time”A landmark estimate reads the curve at one time that was chosen in advance. It is the summary to report when the median is not reached, and it is often easier to explain to a patient than a median. This block reads both curves at 12 months.
landmark <- summary(fit, times = 12)cat(sprintf("%s: S(12) = %.3f, 95%% CI %.3f to %.3f, at risk = %d\n", sub("group=", "", landmark$strata), landmark$surv, landmark$lower, landmark$upper, landmark$n.risk), sep = "")control: S(12) = 0.217, 95% CI 0.123 to 0.327, at risk = 13treated: S(12) = 0.450, 95% CI 0.322 to 0.570, at risk = 27for arm in arms: estimate = fits[arm].predict(12) band = fits[arm].confidence_interval_.loc[:12].iloc[-1] print(f"{arm}: S(12) = {estimate:.3f}, " f"95% CI {band.iloc[0]:.3f} to {band.iloc[1]:.3f}")control: S(12) = 0.217, 95% CI 0.123 to 0.327treated: S(12) = 0.450, 95% CI 0.322 to 0.570At 12 months, 21.7% of the control arm and 45.0% of the treated arm are alive. The intervals, 12.3% to 32.7% and 32.2% to 57.0%, barely overlap. Choose the landmark time before you see the curves. A time picked where the curves are farthest apart overstates the difference.
The log-rank test and the hazard ratio
Section titled “The log-rank test and the hazard ratio”The log-rank test asks whether the arms would show this large a difference in deaths if both had the same hazard at every time. It compares the observed deaths in each arm with the deaths expected under that null model, at every event time.
print(survdiff(Surv(time, event) ~ group, data = df))Call:survdiff(formula = Surv(time, event) ~ group, data = df)
N Observed Expected (O-E)^2/E (O-E)^2/Vgroup=control 60 58 43.4 4.89 8.3group=treated 60 52 66.6 3.19 8.3
Chisq= 8.3 on 1 degrees of freedom, p= 0.004control = df[df["group"] == "control"]treated = df[df["group"] == "treated"]log_rank = logrank_test(control["time"], treated["time"], control["event"], treated["event"])print(f"Log-rank chi-square = {log_rank.test_statistic:.2f}, " f"p = {log_rank.p_value:.4f}")Log-rank chi-square = 8.30, p = 0.0040The treated arm has 52 deaths where equal hazards predict 66.6, and the control arm has 58 where they predict 43.4. The chi-square statistic is 8.3 and p = 0.004: with equal hazards, a gap this large would appear in about 4 trials in 1000.
The test gives no size. A Cox model with the arm as its only covariate supplies the matching estimate, the hazard ratio, and the Cox regression page covers the model itself.
cox_fit <- coxph(Surv(time, event) ~ group, data = df)hazard_ratio <- summary(cox_fit)$conf.intcat(sprintf("Hazard ratio, treated vs control: %.2f, 95%% CI %.2f to %.2f\n", hazard_ratio[1, "exp(coef)"], hazard_ratio[1, "lower .95"], hazard_ratio[1, "upper .95"]))Hazard ratio, treated vs control: 0.58, 95% CI 0.39 to 0.84df["treated"] = (df["group"] == "treated").astype(int)cox_fit = CoxPHFitter().fit(df[["time", "event", "treated"]], duration_col="time", event_col="event")ratio = cox_fit.summary.loc["treated"]print(f"Hazard ratio, treated vs control: {ratio['exp(coef)']:.2f}, " f"95% CI {ratio['exp(coef) lower 95%']:.2f} to " f"{ratio['exp(coef) upper 95%']:.2f}")Hazard ratio, treated vs control: 0.58, 95% CI 0.39 to 0.84The death rate in the treated arm is 0.58 times the rate in the control arm, and ratios from 0.39 to 0.84 are compatible with the data. The true ratio of the simulation, 0.5, lies inside that interval. Report the ratio with the absolute numbers from the sections above: a median of 11.0 against 5.4 months, and 45% against 22% alive at 12 months.
Median follow-up
Section titled “Median follow-up”A reader needs to know how long the patients were watched, because a 24-month survival estimate from a study with 9 months of follow-up rests on few patients. The median of the observed times answers the wrong question: it is short when patients die early, whatever the length of the study. The reverse Kaplan-Meier method swaps the roles. It treats a censored time as the event and a death as censoring, so it estimates how long a patient would have been followed had the patient not died.
reverse_fit <- survfit(Surv(time, 1 - event) ~ 1, data = df)cat(sprintf("Median follow-up, reverse Kaplan-Meier: %.1f months\n", quantile(reverse_fit, 0.5)$quantile))cat(sprintf("Median observed time: %.1f months\n", median(df$time)))Median follow-up, reverse Kaplan-Meier: 30.0 monthsMedian observed time: 7.8 monthsreverse_fit = KaplanMeierFitter().fit(df["time"], 1 - df["event"])print("Median follow-up, reverse Kaplan-Meier: " f"{reverse_fit.median_survival_time_:.1f} months")print(f"Median observed time: {df['time'].median():.1f} months")Median follow-up, reverse Kaplan-Meier: 30.0 monthsMedian observed time: 7.8 monthsThe median follow-up is 30.0 months, and the median observed time is 7.8 months. The second number describes how fast these patients died. The first describes the study: each patient could be followed for 30 months, and here the answer is exact because the only censoring is the cutoff at 30 months. In a trial with staggered entry and dropout, the reverse curve has many steps and its median comes with an interval.
Restricted mean survival time
Section titled “Restricted mean survival time”The restricted mean survival time, RMST, is the area under the survival curve up to a horizon. It is the average time alive during that window. This block uses a horizon of 24 months, so each RMST is the mean number of months lived out of the first 24.
In R, rmst2() from survRM2 takes the arm as 0 or 1 and returns the RMST of each arm, their difference, and the interval of the difference. In lifelines, restricted_mean_survival_time() integrates one fitted curve.
rmst <- rmst2(time = df$time, status = df$event, arm = as.integer(df$group == "treated"), tau = 24)by_arm <- rbind(treated = rmst$RMST.arm1$rmst, control = rmst$RMST.arm0$rmst)cat(sprintf("%s: RMST = %.2f months, 95%% CI %.2f to %.2f\n", rownames(by_arm), by_arm[, "Est."], by_arm[, "lower .95"], by_arm[, "upper .95"]), sep = "")contrast <- rmst$unadjusted.result["RMST (arm=1)-(arm=0)", ]cat(sprintf("Difference: %.2f months, 95%% CI %.2f to %.2f, p = %.3f\n", contrast["Est."], contrast["lower .95"], contrast["upper .95"], contrast["p"]))treated: RMST = 12.22 months, 95% CI 10.05 to 14.39control: RMST = 7.97 months, 95% CI 6.12 to 9.81Difference: 4.25 months, 95% CI 1.40 to 7.10, p = 0.003rmst = {}for arm in ["treated", "control"]: rmst[arm] = restricted_mean_survival_time(fits[arm], t=24) print(f"{arm}: RMST = {rmst[arm]:.2f} months")print(f"Difference: {rmst['treated'] - rmst['control']:.2f} months")treated: RMST = 12.22 monthscontrol: RMST = 7.97 monthsDifference: 4.25 monthsOver the first 24 months, a treated patient lives 12.22 months on average and a control patient 7.97 months. Treatment adds 4.25 months of life within that window, with a 95% interval from 1.40 to 7.10 months.
lifelines returns the same RMST for each arm and no interval. Its return_variance=True option gives the variance of the restricted survival time among patients, which is a different quantity from the squared standard error of the RMST. Take the interval of the difference from rmst2(), or bootstrap the patients within each arm.
The RMST difference is the better summary when the curves cross or the hazards are not proportional. In those trials the hazard ratio has no single value, and the log-rank test can return a large p-value for two arms that differ early in one direction and late in the other. A difference in months lived keeps a plain meaning whatever the shape of the curves. The result depends on the horizon, so fix the horizon in the protocol and keep it inside the follow-up of both arms.
Pitfalls and bioinformatics notes
Section titled “Pitfalls and bioinformatics notes”- Censoring must be unrelated to prognosis. The estimator assumes that a censored patient had the same risk as the patients who stayed. Patients who leave a study because they are getting worse break that assumption, and the curve then sits too high.
- The median may not be reached. If more than half of an arm is event-free at the end of follow-up, the data cannot estimate the median, although the median of the population can lie beyond that follow-up. Report the survival at a landmark time or the RMST.
- The log-rank test is most sensitive when one hazard is a constant multiple of the other. When the curves cross, early and late differences cancel in the statistic, so a large p-value says little about whether the arms differ.
- Do not split a continuous biomarker at its median to draw two curves. The split discards information, and a cut point chosen to separate the curves produces small p-values from noise. Model the biomarker as a continuous covariate with Cox regression.
Key points
Section titled “Key points”- Kaplan-Meier estimates a survival curve from censored times without assuming a distribution.
- Report an estimate with an interval next to the log-rank p-value: a hazard ratio, a landmark survival, or an RMST difference.
- A median that differs between R and lifelines usually means that a step of the curve sits exactly on 0.5.
- Show the number at risk under the curve, and report the median follow-up from the reverse Kaplan-Meier method.
Scientific references
Section titled “Scientific references”The survival package by Therneau supplies the Kaplan-Meier, Cox, and parametric survival models in R.
Davidson-Pilon, 2019 describes lifelines, the Python library for survival analysis.
The survRM2 package by Uno and colleagues compares the restricted mean survival time of two groups.
Kaplan and Meier, 1958 describe the product-limit estimator of a survival curve from censored observations.
Royston and Parmar, 2013 describe the restricted mean survival time as an alternative to the hazard ratio in randomized trials.
Further reading
Section titled “Further reading”The survival curve reference lists the conf.type options. The quantile reference for survival curves explains the tolerance that decides when a step equals a quantile.
The ggsurvfit risk table reference lists the other rows that the table can show, such as cumulative events and censored patients.
The survRM2 vignette covers the ratio of RMST, the restricted mean time lost, and the adjustment for covariates, none of which this page uses.
The lifelines introduction to survival analysis shows the other univariate fitters, including the Nelson-Aalen estimate of the cumulative hazard.
Schemper and Smith, 1996 describe the reverse Kaplan-Meier estimate of follow-up next to the other ways to quantify the follow-up of a study. Read it before you choose the follow-up summary of a report.
The Cox regression lesson adds covariates to the comparison of the two arms.