Display multiple graphs in a list using grid.arrange in R

I want to display several graphs depending on the length of my predictors. I created two lists and then used the grid.arrange function to display graphs in these lists, but I get the following error message - 'only 'grobs' allowed in "gList" . Even when I try to use only one list, say p, I get the same error message. Please, help!

  library(ggplot2) library(gridExtra) # dependent1 variable # dependent2 variable # predictor_vector is a vector of predictors plot_output(data, dependent1, dependent2, predictor_vector) { length<-length(predictor_vector) p<-list() g<-list() for( i in 1:length) { p[[i]]<-ggplot(data, aes(y=dependent1, x=predictor_vector[i])) g[[i]]<-ggplot(data, aes(y=dependent2, x=predictor_vector[i])) } do.call("grid.arrange", c(p, g, list(ncol=2))) } 
+4
source share
1 answer

Posting as an answer is only to show an example that cannot be done in a comment.

The idiom you are trying to use is correct:

 library(ggplot2) library(gridExtra) p <- list(ggplot(mtcars, aes(x=wt, y=mpg))+geom_point(col="black"), ggplot(mtcars, aes(x=wt, y=mpg))+geom_point(col="orange"), ggplot(mtcars, aes(x=mpg, y=wt))+geom_point(col="blue")) g <- list(ggplot(mtcars, aes(x=wt, y=mpg))+geom_point(col="red"), ggplot(mtcars, aes(x=mpg, y=wt))+geom_point(col="green")) do.call(grid.arrange, c(p, g, list(ncol=2))) 

enter image description here

Two lists of ggplot objects of variable length, followed by a list of parameters. You need to provide data and a more complete cycle for us to find out how to help you understand what you are doing wrong.

+10
source

All Articles