Answer

What is survival analysis? Kaplan-Meier curves and hazard ratios explained

A frequently asked statistics question ·

survival analysisregressionhypothesis testing

The short answer

Survival analysis models the time until an event happens, such as death, relapse, machine failure or a customer cancelling. Its key feature is that it uses people whose event has not happened yet (censored observations) instead of dropping them. A Kaplan-Meier curve shows the share still event-free over time, the log-rank test compares curves, and a Cox model gives a hazard ratio: the event rate in one group relative to another at any moment.

What survival analysis is for

Survival analysis is the set of methods for time-to-event outcomes: how long until something happens. The name comes from medicine, where the event is often death, but the same tools are used for time to relapse, to finding a job, to a machine part failing, to a customer cancelling a subscription, or to a student dropping out.

Two features make this kind of data awkward for ordinary methods. First, times are positive and usually right-skewed, so a mean and a t test describe them poorly. Second, and more important, the study usually ends before everyone has had the event. Someone followed for 18 months without relapsing tells you their time to relapse is more than 18 months, not what it is. Survival methods are built to use that partial information correctly.

Censoring, and how it differs from truncation

An observation is censored when you know the event time only partly. The common case is right censoring: the person was event-free when you last saw them, because the study ended, they moved away, or they withdrew. Left censoring (the event happened before a known time) and interval censoring (it happened between two visits) also occur.

Dropping censored people, or treating their last contact as the event time, both bias the results: the first throws away the people who did best, and the second pretends they had the event. Survival methods instead keep each person in the calculation for as long as they were observed. That is valid when censoring is non-informative, meaning that people who leave the study are not systematically at higher or lower risk than those who stay. If the sickest patients drop out, no method fixes that from the data alone.

Truncation is different. With censoring, the person is in your data with an incomplete time. With truncation, some people never enter your data at all because of their event time. The usual example is left truncation (delayed entry): a study that recruits people already living with a condition can only include those who survived long enough to be recruited. Analyses handle this by counting each person as at risk only from their entry time, not from the time origin.

How to read a Kaplan-Meier curve

The Kaplan-Meier estimator gives the survival curve: the estimated probability of still being event-free at each time. At every event time it multiplies the running total by one minus the share of people still at risk who had the event then. Censored people count as at risk until they leave, then drop out of the denominator without moving the curve.

Hazard ratios and the Cox model

The hazard is the instantaneous event rate among people who have not had the event yet: roughly, the chance of the event in the next short interval, given that you have made it this far, divided by the length of that interval. A hazard ratio (HR) compares two groups' hazards. An HR of 0.70 means that at any point in follow-up, the treated group has events at 70% of the rate of the control group, a 30% lower hazard. An HR of 2 means twice the rate.

The Cox proportional hazards model is the regression model of survival analysis. Like other regressions it can include several predictors at once, and each coefficient is a log hazard ratio, so exponentiating it gives the HR adjusted for the other predictors. It leaves the shape of the baseline hazard unspecified, which is why it is so widely used. Its main assumption is proportional hazards: the HR stays the same over time. Check it, for example with cox.zph() in R's survival package, and look for curves that cross.

Two common misreadings: an HR is not a ratio of median survival times, and it is not the ratio of the share who eventually have the event. It is a ratio of rates at each moment.

An example in R and Python

In practice you would use R's survival package (Surv(), survfit(), survdiff() and coxph()) or, in Python, a library such as lifelines. To show what those functions compute, the code below does it by hand with base R and with NumPy and SciPy. It simulates 100 patients per group, with the treatment lowering the true hazard by 40% (HR = 0.6), random dropout, and the study ending at 24 months.

R

set.seed(3)
n <- 100                                    # patients per group
group <- rep(c(0, 1), each = n)             # 0 = control, 1 = treatment
event_time <- rexp(2 * n, rate = 0.10 * 0.6^group)   # true hazard ratio 0.6
censor_time <- pmin(runif(2 * n, 0, 40), 24)          # dropout; study ends at 24 months
time <- pmin(event_time, censor_time)
status <- as.numeric(event_time <= censor_time)       # 1 = event, 0 = censored
table(group, status)

# Kaplan-Meier: multiply (1 - events / number at risk) over the event times
km <- function(t, d) {
  times <- sort(unique(t[d == 1]))
  data.frame(time = times, surv = cumprod(sapply(times, function(u) 1 - sum(t == u & d == 1) / sum(t >= u))))
}
km_c <- km(time[group == 0], status[group == 0])
km_t <- km(time[group == 1], status[group == 1])
summ <- function(k) c(median = if (any(k$surv <= 0.5)) min(k$time[k$surv <= 0.5]) else NA,
                      surv_12m = tail(c(1, k$surv[k$time <= 12]), 1))
round(rbind(control = summ(km_c), treatment = summ(km_t)), 3)

# Log-rank test and Cox model, both built from the risk set at each event time
b <- 0
for (iter in 1:25) {                        # Newton-Raphson for the Cox coefficient
  O <- E <- V <- U <- I <- 0
  for (i in which(status == 1)) {
    at_risk <- time >= time[i]
    p0 <- mean(group[at_risk])              # share of the risk set that is treated
    p <- sum(group[at_risk] * exp(b)) / sum(exp(b * group[at_risk]))
    O <- O + group[i]; E <- E + p0; V <- V + p0 * (1 - p0)
    U <- U + group[i] - p; I <- I + p * (1 - p)
  }
  b <- b + U / I
}
logrank <- (O - E)^2 / V
round(c(observed = O, expected = E, chisq = logrank, p = pchisq(logrank, 1, lower.tail = FALSE)), 4)
se <- sqrt(1 / I)
round(c(HR = exp(b), lower = exp(b - 1.96 * se), upper = exp(b + 1.96 * se), p = 2 * pnorm(-abs(b / se))), 4)

Python

import numpy as np
import pandas as pd
from scipy import stats

rng = np.random.default_rng(3)
n = 100                                              # patients per group
group = np.repeat([0, 1], n)                         # 0 = control, 1 = treatment
event_time = rng.exponential(1 / (0.10 * 0.6**group))   # true hazard ratio 0.6
censor_time = np.minimum(rng.uniform(0, 40, 2 * n), 24)  # dropout; study ends at 24 months
time = np.minimum(event_time, censor_time)
status = (event_time <= censor_time).astype(int)     # 1 = event, 0 = censored
print(pd.crosstab(group, status, rownames=["group"], colnames=["status"]))

# Kaplan-Meier: multiply (1 - events / number at risk) over the event times
def km(t, d):
    times = np.sort(np.unique(t[d == 1]))
    factors = [1 - np.sum((t == u) & (d == 1)) / np.sum(t >= u) for u in times]
    return times, np.cumprod(factors)

def summ(t, d):
    times, surv = km(t, d)
    median = times[surv <= 0.5].min() if np.any(surv <= 0.5) else np.nan
    surv_12m = np.concatenate([[1.0], surv[times <= 12]])[-1]
    return round(float(median), 3), round(float(surv_12m), 3)

for name, g in [("control", 0), ("treatment", 1)]:
    print(name, "median, surv_12m:", summ(time[group == g], status[group == g]))

# Log-rank test and Cox model, both built from the risk set at each event time
b = 0.0
for _ in range(25):                                  # Newton-Raphson for the Cox coefficient
    O = E = V = U = I = 0.0
    for i in np.flatnonzero(status == 1):
        g = group[time >= time[i]]
        p0 = g.mean()                                # share of the risk set that is treated
        p = np.sum(g * np.exp(b)) / np.sum(np.exp(b * g))
        O += group[i]; E += p0; V += p0 * (1 - p0)
        U += group[i] - p; I += p * (1 - p)
    b += U / I

logrank = (O - E) ** 2 / V
print("log-rank: observed", O, "expected", round(E, 4), "chisq", round(logrank, 4),
      "p", round(stats.chi2.sf(logrank, 1), 4))
se = np.sqrt(1 / I)
print("Cox HR", round(np.exp(b), 4), "95% CI", round(np.exp(b - 1.96 * se), 4),
      round(np.exp(b + 1.96 * se), 4), "p", round(2 * stats.norm.sf(abs(b / se)), 4))
     status
group  0  1
    0 29 71
    1 35 65
          median surv_12m
control    7.013    0.329
treatment 11.518    0.459
observed expected    chisq        p 
 65.0000  77.3118   4.6347   0.0313 
    HR  lower  upper      p 
0.6896 0.4907 0.9690 0.0323

These figures come from one seeded run of the R code. Python's random numbers differ from R's, so its estimates differ (in its draw the treatment effect looks larger), but the pattern is the same: fewer treated events than expected, a longer median and a hazard ratio below 1. That gap between two simulated samples of 200 is itself a reminder of how much a single study can vary.

When to use survival analysis instead of logistic regression

A tempting shortcut is to turn the outcome into yes/no ("had the event within two years?") and fit a logistic regression. That works only when everyone was followed for the full window and the timing within it does not matter. Otherwise survival analysis is the better tool, because:

If you are unsure which analysis fits your design, the test chooser and the DASS statistics tools are good starting points.

How to report a hazard ratio in APA style (7th edition)

Report the number of events and censored observations, the median survival time per group (or "not reached"), the log-rank test if you used one, and the hazard ratio with its confidence interval. State in the method section how censoring was defined and how the proportional hazards assumption was checked. Using the example above:

"Of 200 patients, 136 experienced the event and 64 were censored. Median time to the event was 7.0 months in the control group and 11.5 months in the treatment group, log-rank χ²(1) = 4.63, p = .031. In a Cox proportional hazards model, treatment was associated with a lower hazard of the event, HR = 0.69, 95% CI [0.49, 0.97], p = .032."

A Kaplan-Meier figure with a number-at-risk table under the time axis is the clearest way to show the curves; for models with several predictors, give a table with each HR and its 95% CI.

Related tools and guides

More answered questions

Working with your own data?

General answers only go so far. Send us your situation and we'll reply by email within two business days.

Ask your question

Need more than an answer?

Written by AskStats with AI assistance. This is general information, not advice for your specific data or study. When the results matter, check your approach with a qualified statistician.