Diego
Diego

Reputation: 36146

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)

enter image description here

anything that can be done there?

Thanks, Diego

Upvotes: 0

Views: 119

Answers (2)

Heroka
Heroka

Reputation: 13139

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

enter image description here

Upvotes: 1

Roman Luštrik
Roman Luštrik

Reputation: 70643

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)

Upvotes: 0

Related Questions