3

I have several graphs that I would like to put into the grid.arrange function. However, I do not always know in advance how many graphs will have to be in the grid and want to avoid having to go through the code consistently to change every grid.arrange function.

gg1 <- ggplot(mtcars, aes(cyl)) + geom_bar()
gg2 <- ggplot(mpg, aes(class, hwy)) + geom_bar(stat = "identity")
gg3 <- ggplot(mpg, aes(hwy)) + geom_area(stat = "bin")              

grid.test <- grid.arrange(gg1,gg2,gg3)

I have already tried pasting the items.

grid.arrange(paste("gg", 1:3, sep= ""))

I also tried putting them into a list and parsing that but cannot get an undefined amount of them in grid.arrange. Especially as grid.arrange only accepts it if you grab the elements, which doesn't allow multiple selection.

ggtest <- list(gg1,gg2,gg3)

grid.test <- grid.arrange(ggtest[[1:3]])

Returns Subscript error

ggtest <- list(gg1,gg2,gg3)

grid.test <- grid.arrange(ggtest[1:3])

returns only 'grobs' allowed in "gList" error.

Any help welcome here, perhaps I am looking at it the wrong way or is there another function that should be used?

M--
  • 25,431
  • 8
  • 61
  • 93
Thejohn
  • 91
  • 9
  • 3
    ```ggtest <- mget(paste0("gg", 1:3)); do.call(grid.arrange, ggtest)``` – M-- Jul 09 '19 at 19:57
  • 3
    In addition to @M-M's comment you may also try `ggtest <- mget(ls(pattern = "^gg\\d+$")` first. – markus Jul 09 '19 at 20:02
  • 4
    maybe worth noting that you should probably be putting these plots in a list to begin with (when they're created), rather than scattering them in your global environment and then searching for them after the fact with `mget` – IceCreamToucan Jul 09 '19 at 20:07

1 Answers1

3
library(gridExtra)
library(ggplot2)

gg1 <- ggplot(mtcars, aes(cyl)) + geom_bar()
gg2 <- ggplot(mpg, aes(class, hwy)) + geom_bar(stat = "identity")
gg3 <- ggplot(mpg, aes(hwy)) + geom_area(stat = "bin")              

ggtest <- mget(paste0("gg", 1:3))

do.call(grid.arrange, ggtest)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

M--
  • 25,431
  • 8
  • 61
  • 93