Skip to content

Cox Proportional Hazards

A Kaplan-Meier curve compares whole groups. It cannot adjust the comparison for a second variable, and it has no way to use a continuous predictor without cutting it into groups. Cox proportional hazards regression does both. Its output is the hazard ratio, the standard effect measure of survival studies.

This page fits a Cox model with a treatment arm and a continuous biomarker, reads the two hazard ratios, checks the assumption that gives the model its name, and fits the two standard alternatives for a covariate that breaks it.

Use it for time-to-event data when you want the effect of each covariate adjusted for the others. The model leaves the baseline hazard unspecified, so you do not choose a distribution for the survival times. What it does assume is that each covariate multiplies the hazard by the same factor at every time.

Download cox_data.csv into your working directory. The invented table holds 150 patients, one row per patient, with four columns: time is the follow-up in months, event is 1 for a death and 0 for a censored time, group is 0 for control and 1 for treated, and biomarker is a continuous baseline measurement on a standardized scale.

The times come from a simulation with known answers. Treatment multiplies the hazard by 0.50, each unit of the biomarker multiplies it by 1.65, and both factors stay constant over time. The data cutoff falls at 30 months, which censors 27 patients and leaves 123 deaths.

library(survival)
library(broom)
library(ggplot2)
df <- read.csv("cox_data.csv")
df$group <- factor(df$group, levels = c(0, 1),
labels = c("control", "treated"))
dir.create("outputs", showWarnings = FALSE)
fit <- coxph(Surv(time, event) ~ group + biomarker, data = df)
print(summary(fit), signif.stars = FALSE)
Call:
coxph(formula = Surv(time, event) ~ group + biomarker, data = df)
n= 150, number of events= 123
coef exp(coef) se(coef) z Pr(>|z|)
grouptreated -1.0750 0.3413 0.1888 -5.693 1.25e-08
biomarker 0.4473 1.5641 0.1102 4.059 4.92e-05
exp(coef) exp(-coef) lower .95 upper .95
grouptreated 0.3413 2.9301 0.2357 0.4941
biomarker 1.5641 0.6394 1.2603 1.9411
Concordance= 0.664 (se = 0.027 )
Likelihood ratio test= 44.15 on 2 df, p=3e-10
Wald test = 42.21 on 2 df, p=7e-10
Score (logrank) test = 44.99 on 2 df, p=2e-10

The two tools print the same coefficients, standard errors, and intervals to four decimals. Both handle tied event times with the Efron approximation by default. A few deaths in this table share a time because the times are rounded to 0.01 month, and the shared default means that those ties cause no difference between the tabs.

The hazard is the death rate at a given moment among the patients who are still alive at that moment. The hazard ratio is exp(coef), and a ratio of 1 means no association.

For treatment the ratio is 0.34, with a 95% interval from 0.24 to 0.49. At any time, treated patients who are still alive die at about a third of the rate of controls who are still alive and have the same biomarker value. The interval excludes the true ratio of the simulation, 0.50, by a small margin. An interval with 95% coverage misses in about one data set in twenty, and this table is one of them.

For the biomarker the ratio is 1.56, with an interval from 1.26 to 1.94. Each additional unit multiplies the death rate by 1.56 within either arm. Two units multiply it by 1.56 squared, about 2.4, because the model is linear on the log scale.

The concordance of 0.664 is the proportion of comparable patient pairs in which the patient with the higher predicted risk died first. A value of 0.5 is a coin toss and 1 is a perfect ranking.

A forest plot draws each ratio with its interval on a log axis, where 0.5 and 2 sit at the same distance from 1.

ratios <- tidy(fit, exponentiate = TRUE, conf.int = TRUE)
forest_plot <- ggplot(ratios, aes(x = estimate, y = term)) +
geom_vline(xintercept = 1, linetype = "dashed", color = "grey50") +
geom_pointrange(aes(xmin = conf.low, xmax = conf.high),
color = "#1f4e5f") +
scale_x_log10(breaks = c(0.25, 0.5, 1, 2)) +
labs(x = "Hazard ratio (log scale)", y = NULL) +
theme_minimal(base_size = 13)
ggsave("outputs/cox-forest-r.png", forest_plot, width = 5.5, height = 3,
dpi = 150)

Forest plot from ggplot2 with one row for the treated arm and one for the biomarker. The treatment hazard ratio and its interval lie left of the dashed line at 1, and the biomarker ratio and its interval lie right of it.

The model assumes that each hazard ratio is one number for the whole follow-up. If the biomarker matters more late than early, the single ratio of 1.56 is an average over time that describes neither period.

Both languages test the assumption from the scaled Schoenfeld residuals. Each death contributes one residual per covariate, and a trend in the residuals over time means that the coefficient changes over time.

zph <- cox.zph(fit)
print(zph)
chisq df p
group 0.772 1 0.380
biomarker 5.161 1 0.023
GLOBAL 5.354 2 0.069

R reports p = 0.023 for the biomarker. lifelines reports p = 0.031 and then prints that the assumption looks okay. The contrast comes from a threshold and from the test statistic, and neither one is a disagreement about the data.

The message comes from a threshold. check_assumptions() flags a covariate only when its p-value, rounded to two decimals, is at or below p_value_threshold, and the default threshold is 0.01. The biomarker’s 0.03 is above it. Call check_assumptions(df, p_value_threshold=0.05) and the same function reports that the biomarker failed the test. “Looks okay” means that no p-value came down to 0.01, so read the table from proportional_hazard_test() instead of the message.

The p-values differ because the statistics differ. cox.zph() computes a score test. lifelines computes the faster approximation that the survival package used before version 3.0, as the lifelines documentation states, and it prints no global test. The time scale matters less here: R tests against the Kaplan-Meier transform of time by default and lifelines against the rank of time, and the two lifelines rows show that the choice moves the biomarker’s p-value from 0.031 to 0.030.

A p-value from either tool is the probability of a trend at least this strong when the hazards are proportional. For this table we know that they are, because the simulation used a constant ratio, and the biomarker still gets 0.023. That is the expected behavior of a test: with proportional hazards, about one covariate in twenty falls below 0.05. The reverse reading fails too. The p-values of 0.380 for the arm and 0.069 for the global test do not show that those hazards are proportional, since a trial with 123 deaths can miss a slow drift. A test cannot settle the question in either direction, so look at how large the drift is.

The plot of the scaled Schoenfeld residuals against time estimates the coefficient as a function of time. In R, plot() on the cox.zph object adds the fitted coefficient to each residual and draws a spline with a band of two standard errors. lifelines returns the residuals from compute_residuals(), centered on zero, so the Python code adds the coefficient and draws a lowess curve. The dashed orange line marks the constant coefficient of the model, 0.447.

png("outputs/cox-schoenfeld-r.png", width = 6, height = 4, units = "in",
res = 150)
par(mar = c(4.5, 4.5, 1, 1))
plot(zph, var = "biomarker", xlab = "Time (months)",
ylab = "Coefficient of biomarker")
abline(h = coef(fit)["biomarker"], lty = 2, lwd = 2, col = "#e07a5f")
invisible(dev.off())

Scaled Schoenfeld residuals of the biomarker from cox.zph against time. The spline lies below the dashed line at the fitted coefficient for about the first 6 months, rises above it to about 0.8 near 12 months, and the band of two standard errors contains the line over most of the range.

Under proportional hazards the curve is flat and follows the dashed line. Here it lies below the line for about the first 6 months and above it afterward, so the biomarker matters less for an early death than for a late one in this table. The drift is modest next to its uncertainty: the band in the R plot contains the dashed line, or nearly so, across the whole range.

Both axes space the deaths evenly. The first 6 months hold about half of the deaths, so they take about half of the width.

Two standard models relax the assumption. The first lets a coefficient change with time. The second, for a categorical covariate, gives each level its own baseline hazard.

Split each patient’s follow-up at a cut time, then give the biomarker one coefficient before the cut and one after it. The cut here is 6 months, where about half of the deaths have occurred. survSplit() in R makes one row per patient and period. to_episodic_format() in lifelines makes one row per patient for every 6 months of follow-up, and CoxTimeVaryingFitter fits the rows. The number of rows differs between the tabs, and the fit does not, because cutting a row at a time when its covariates do not change leaves the partial likelihood as it was.

long <- survSplit(Surv(time, event) ~ ., data = df, cut = 6,
episode = "period")
long$biomarker_early <- long$biomarker * (long$period == 1)
long$biomarker_late <- long$biomarker * (long$period == 2)
cat(sprintf("%d rows, %d deaths before 6 months, %d after\n", nrow(long),
sum(long$event[long$period == 1]),
sum(long$event[long$period == 2])))
split_fit <- coxph(Surv(tstart, time, event) ~ group + biomarker_early +
biomarker_late, data = long)
ratio_columns <- c("exp(coef)", "lower .95", "upper .95")
print(round(summary(split_fit)$conf.int[, ratio_columns], 2))
234 rows, 66 deaths before 6 months, 57 after
exp(coef) lower .95 upper .95
grouptreated 0.33 0.23 0.48
biomarker_early 1.20 0.91 1.60
biomarker_late 2.22 1.59 3.09

In the first 6 months, one unit of the biomarker multiplies the death rate by 1.20, with an interval from 0.91 to 1.60. After 6 months it multiplies the rate by 2.22, with an interval from 1.59 to 3.09. The treatment ratio barely moves, from 0.34 to 0.33. A report from this model gives both periods, since the single ratio of 1.56 from the first model sits between them.

Remember what the table is. The simulation used a constant ratio of 1.65, so the gap between 1.20 and 2.22 is sampling variation, and the early interval even stops short of the true value. Real data carry no such answer key. Fix the cut time before you look at the residual plot, because a cut chosen where the curve bends exaggerates the gap, and ask whether the biology gives a reason for the effect to change.

For a smooth change in place of a step, coxph() has a tt argument that multiplies a covariate by a function of time. lifelines has no equivalent argument, and its route is the long table above with a finer split.

Stratification is the remedy for a categorical covariate. The model estimates a separate baseline hazard of any shape for each level, so that covariate no longer needs proportional hazards. The cost is that it gets no coefficient. This block stratifies on the treatment arm to show the mechanics.

strata_fit <- coxph(Surv(time, event) ~ biomarker + strata(group),
data = df)
print(round(summary(strata_fit)$conf.int[, ratio_columns, drop = FALSE], 2))
exp(coef) lower .95 upper .95
biomarker 1.55 1.25 1.92

The biomarker ratio is 1.55, close to the 1.56 of the first model, and the output has no row for the arm. That is the reason to stratify on a nuisance factor such as study site or disease stage and never on the treatment whose effect the trial must report. The arm in this table was simulated with proportional hazards, so the first model is the right one for it.

  • A hazard ratio is a ratio of rates, and it is a different number from a ratio of risks. A ratio of 0.34 does not mean that a third as many treated patients have died by 12 months, and it does not mean that they live three times as long. Report the survival of each arm at a landmark time from the Kaplan-Meier curves next to the ratio.
  • The precision of a Cox model depends on the number of events more than on the number of patients. A common rule of thumb asks for at least ten events for each coefficient, and this table has 123 deaths for two coefficients.
  • A hazard ratio is per one unit of the covariate. The biomarker here is standardized, so its ratio is per standard deviation. For a covariate in raw units, such as age in years, the ratio per unit looks close to 1 even when the effect is large. Divide the covariate by a meaningful step, such as 10 years, before the fit. The rescaling changes the ratio and leaves the z statistic and the p-value as they were.
  • A stratified or time-split model changes what the other ratios mean. After stratification, the biomarker ratio compares patients within the same stratum only.
  • Cox regression models the hazard as a product of a baseline hazard and one factor per covariate, and it reports those factors as hazard ratios with intervals.
  • R and lifelines give the same fit. Their proportional hazards tests use different statistics, and the lifelines message depends on a threshold of 0.01.
  • A residual test with a small p-value does not prove a drift, and a large one does not prove proportional hazards. Plot the scaled Schoenfeld residuals and judge the size of the drift.
  • When a ratio changes over time, split the follow-up and report one ratio per period, or stratify on a categorical nuisance factor.

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.

Cox, 1972 describes the proportional hazards regression model and its partial likelihood.

Grambsch and Therneau, 1994 describe the tests and plots of proportional hazards that use scaled Schoenfeld residuals.

The coxph reference documents the ties, strata, and tt options that this page mentions. The cox.zph reference lists the time transforms of the test and notes the change to a score test in version 3.0.

The survSplit reference explains the start, stop, and episode columns of the long table, including splits at more than one cut time.

The lifelines page on testing the proportional hazard assumption works through stratification, a changed functional form, and time-varying covariates on one data set.

An Introduction to Statistical Learning has a survival analysis chapter with labs in its R and Python editions.

Continue with Competing Risks when a second kind of event can prevent the event of interest.