以小平面方式堆叠不同的地块 [英] Stacke different plots in a facet manner
问题描述
facet_grid
选项,但是我没有设法使用这个函数。我不希望这两块地块粘在一起,就像我们可以用 grid.arrange
做的那样,而是要有相同的x轴。 以下代码生成两个(简化)图,我想将它们堆叠在一起。我试图用 facet_grid
来做到这一点,但我不认为解决方案在于这个
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 $ )
pl1 < - ggplot(dat,aes(time,surv))+ geom_step()
pl2 < - ggplot(dat,aes(time,nr))+ geom_area()
首先,将数据融化为长格式。
library(reshape2 )
dat.long< -melt(dat,id.vars =time)
head(dat.long)
时间变量值
1 0存活1.00000 00
2 5生存0.9956140
3 11生存0.9824561
4 12生存0.9780702
5 13生存0.9692982
6 15生存0.9649123
然后使用 subset()
来仅使用 code中的数据
geom_step()
和 nr
中的数据geom_area()
和 facet_grid()
,您将在单独的方面获得每个图,因为变量
用于为分面和子集划分数据。 scales =free_y
会使漂亮的轴线变得美丽。
$ b
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(变量〜。,scales =free_y)
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()
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")
这篇关于以小平面方式堆叠不同的地块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!