I would like to control the layout when plotting a series of ggplots that I have stored in a list (generated automatically elsewhere).
I can plot series of plots as below.
library(ggplot2)
library(grid)
library(gridExtra)
p1 <- ggplot(mtcars, (aes(x=mpg, fill=as.factor(1)))) + geom_density() +
scale_fill_manual(values="red")
p2 <- ggplot(mtcars, (aes(x=mpg, fill=as.factor(1)))) + geom_density() +
scale_fill_manual(values="orange")
p3 <- ggplot(mtcars, (aes(x=mpg, fill=as.factor(1)))) + geom_density() +
scale_fill_manual(values="yellow")
p4 <- ggplot(mtcars, (aes(x=mpg, fill=as.factor(1)))) + geom_density() +
scale_fill_manual(values="green")
grid.arrange(p1, p2, p3, p4)
I can then change their layout, as indicated here.
grid.arrange(p1, p2, p3, p4, layout_matrix=cbind(c(1,2), c(3,4)))
I can also plot a series of plots if they are stored in a list, as indicated here.
myplotslist <- list(p1, p2, p3, p4)
do.call(grid.arrange, c(myplotslist, ncol=2))
But if I try to change the layout using layout_matrix, I get an error (and some warnings).
do.call(grid.arrange, c(myplotslist, ncol=2, layout_matrix=cbind(c(1,2), c(3,4))))
Error in gList(list(grobs = list(list(x = 0.5, y = 0.5, width = 1, height = 1, :
only 'grobs' allowed in "gList"
In addition: Warning messages:
1: In grob$wrapvp <- vp : Coercing LHS to a list
2: In grob$wrapvp <- vp : Coercing LHS to a list
3: In grob$wrapvp <- vp : Coercing LHS to a list
4: In grob$wrapvp <- vp : Coercing LHS to a list
I have tried coercing the plot objects to grobs, but encounter the same error.
myplotslist2 <- list(ggplotGrob(p1), ggplotGrob(p2), ggplotGrob(p3), ggplotGrob(p4))
I am using R 3.2.1, ggplot2 2.0.0, grid 3.2.1, and gridExtra 2.0.0, and would be extremely grateful for suggestions.