Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

r - Stacke different plots in a facet manner

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()

enter image description here

pl2 <- ggplot(dat, aes(time, nr)) + geom_area()

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, melt your data to long format.

library(reshape2)
dat.long<-melt(dat,id.vars="time")
head(dat.long)
  time variable     value
1    0     surv 1.0000000
2    5     surv 0.9956140
3   11     surv 0.9824561
4   12     surv 0.9780702
5   13     surv 0.9692982
6   15     surv 0.9649123

Then use subset() to use only surv data in geom_step() and nr data in geom_area() and with facet_grid() you will get each plot in separate facet as variable is used to divide data for facetting and for subsetting. scales="free_y" will make pretty axis.

ggplot()+geom_step(data=subset(dat.long,variable=="surv"),aes(time,value))+
  geom_area(data=subset(dat.long,variable=="nr"),aes(time,value))+
  facet_grid(variable~.,scales="free_y")

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...