To train with ggplot and to improve my skills in writing R functions I decided to build a series of functions that produces survival plots, with all kinds of extras. I managed to build a good working function for the basic survival plot, now I am getting to the extras. One thing I would like to do is an option that stacks an area plot of the number at risk at a given time point, on top of the survival plot. I would like it to look just like the facet_grid
option of ggplot, but I did not manage to do it with this function. I do not want the two plots binded, like we can do with grid.arrange
, but rather to have the same x-axis.
The following code produces the two (simplified) plots that I would like to stack on top of each other. I tried to do this with facet_grid
, but I don't think the solution lies in this
library(survival)
library(ggplot2)
data(lung)
s <- survfit(Surv(time, status) ~ 1, data = lung)
dat <- data.frame(time = c(0, s$time),
surv = c(1, s$surv),
nr = c(s$n, s$n.risk))
pl1 <- ggplot(dat, aes(time, surv)) + geom_step()
pl2 <- ggplot(dat, aes(time, nr)) + geom_area()
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…