6

I want to display multiple plots depending on the length of my predictors. I have created two list and then used grid.arrange function to display the plots within these lists, but I am getting 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)))

 }
lmo
  • 37,904
  • 9
  • 56
  • 69
devdreamer
  • 159
  • 2
  • 11
  • this is not a reproducible example. you provided no data and the `ggplot`s have no `geom_`s. also, it's not really a good idea to use variable names that are the same as base functions (i.e. `length`). – hrbrmstr Aug 23 '15 at 00:15
  • I had the same problem a while back http://stackoverflow.com/questions/31994387/r-ggplot2-saving-plots-as-r-objects-and-displaying-in-grid – Timo Kvamme Aug 23 '15 at 00:43

1 Answers1

12

Posting as an answer only to show the example that's impossible in a comment.

The idiom you're 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 variable length ggplot object lists and then the parameter list. You need to provide the data and a more complete loop for us to know how to help you figure out what you're doing incorrectly.

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
  • Thank you for your answer. It seems to work now. I think there was some bug in my code because of which I was getting the error message. – devdreamer Aug 23 '15 at 01:20
  • Is it possible to fix the size of the plots in the example you provided? – devdreamer Aug 23 '15 at 01:38
  • not precisely, but you can play around with the grid element proportions in `grid.arrange` (IIRC there are some examples in the `arrangeGrob` help). You can combine what with `coord_fixed` to achieve some semblance of size predictability. – hrbrmstr Aug 23 '15 at 13:25