[英]Multiple boxplots from the same dataset
I'm looking for a way of simplifying the code bellow; 我正在寻找一种简化以下代码的方法; I have 9 different measures that I'd like to plot against quality and am trying to avoid coping and pasting the code 9 times (or even having to write a function to plot and call the function 9 times):
我想根据质量绘制9种不同的度量值,并试图避免对代码进行9次粘贴和粘贴(甚至不得不编写9次函数来绘制和调用函数):
p1<- ggplot(aes(x=quality, y = alcohol), data = df) + geom_boxplot()+ stat_summary(fun.y=mean,geom = 'point', shape = 4)
p2<- ggplot(aes(x=quality, y = pH), data = df) + geom_boxplot()+ stat_summary(fun.y=mean,geom = 'point', shape = 4)
grid.arrange(p1,p2, ncol=1)
anything that can be done there? 有什么可以做的吗?
Thanks, Diego 谢谢迭戈
Using do.call on a list of plots generated by plyr on a melted dataframe. 在由plyr在融化的数据帧上生成的绘图列表上使用do.call。 (I'm assuming there is a reason you do not want to use facet_grid on melted data)
(我假设您不想在融化的数据上使用facet_grid是有原因的)
#generate some data
data <- data.frame(id=1:500, quality=sample(3:10,replace=TRUE,size=500))
for(i in 1:9){
data[,paste0("outcome_",i)]<-rnorm(500)
}
#melt it
melt_data <- melt(data,id.vars=c("id","quality"))
head(melt_data)
library(ggplot2)
library(gridExtra)
#generate a list of plots
plots <- dlply(melt_data,.(variable),function(chunk){
ggplot(data=chunk, aes(x=factor(quality), y = value)) + geom_boxplot()+
stat_summary(fun.y=mean,geom = 'point', shape = 4) +
#label y axis correctly
labs(y=unique(chunk$variable)
)
})
do.call(grid.arrange,c(plots,ncol=2))
You can use do.call
. 您可以使用
do.call
。
library(ggplot2)
p1 <- ggplot(airquality, aes(x = Ozone, y = Solar.R)) +
theme_bw() +
geom_point()
out <- list(p1, p1)
library(gridExtra)
do.call("grid.arrange", out)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.