简体   繁体   中英

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

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. (I'm assuming there is a reason you do not want to use facet_grid on melted data)

#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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM