Skip to content

Instantly share code, notes, and snippets.

@sinhrks
Created October 4, 2014 10:53
Show Gist options
  • Save sinhrks/768ee4ab1488fbb73b77 to your computer and use it in GitHub Desktop.
Save sinhrks/768ee4ab1488fbb73b77 to your computer and use it in GitHub Desktop.
Allow ggplot2 to handle survival::survfit result
library(survival)
library(ggplot2)
library(scales)
d.survfit <- survival::survfit(survival::Surv(time, status) ~ sex,
data = lung)
fortify.survfit <- function(survfit.data) {
data.frame(time = survfit.data$time,
n.risk = survfit.data$n.risk,
n.event = survfit.data$n.event,
n.censor = survfit.data$n.censor,
surv = survfit.data$surv,
std.err = survfit.data$std.err,
upper = survfit.data$upper,
lower = survfit.data$lower,
strata = rep(names(survfit.data$strata), survfit.data$strata))
}
head(ggplot2::fortify(d.survfit))
ggplot(data = d.survfit) +
geom_line(aes_string(x = 'time', y = 'surv', colour = 'strata')) +
geom_ribbon(aes_string(x = 'time', ymin = 'lower', ymax = 'upper', fill = 'strata'), alpha = 0.5) +
scale_y_continuous(labels = scales::percent)
# plot censors
fortified <- ggplot2::fortify(d.survfit)
ggplot(data = fortified) +
geom_line(aes_string(x = 'time', y = 'surv', colour = 'strata')) +
geom_ribbon(aes_string(x = 'time', ymin = 'lower', ymax = 'upper', fill = 'strata'), alpha = 0.5) +
geom_point(data = fortified[fortified$n.censor > 0, ],
aes_string(x = 'time', y = 'surv'), shape = '+', size = 3) +
scale_y_continuous(labels = scales::percent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment