Search code examples
rggplot2gridextrar-grid

Assign grid.arrange to object


I want to arrange plots with grid.arrange to make more complex coplots and then use grid.arrange to combine these complex coplots. I am using the following solution (https://stackoverflow.com/a/13295880/1000343) in this task to arrange mutliple plots and ensure they have equal widths. Here is a demo of the code:

library(ggplot2); library(gridExtra)
gA <- ggplotGrob(A)
gB <- ggplotGrob(B)
maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)

x <- grid.arrange(gA, gB, ncol=1)
y <- grid.arrange(gA, gB, ncol=1)
grid.arrange(x, y, ncol=2)

To be clear in my case x and y are slightly different plots with different values. I know grid.arrange isn't returning the plot as other grid based functions.


Solution

  • If you look at the source code for grid.arrange, it is simply a wrapper for arrangeGrob

    function (..., as.table = FALSE, clip = TRUE, main = NULL, sub = NULL, 
        left = NULL, legend = NULL, newpage = TRUE) 
    {
        if (newpage) 
            grid.newpage()
        grid.draw(arrangeGrob(..., as.table = as.table, clip = clip, 
            main = main, sub = sub, left = left, legend = legend))
    }
    

    Therefore

    require(ggplot2);require(gridExtra)
    A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +coord_flip() 
    B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip() 
    gA <- ggplotGrob(A)
    gB <- ggplotGrob(B)
    maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
    gA$widths[2:5] <- as.list(maxWidth)
    gB$widths[2:5] <- as.list(maxWidth)
    x <- arrangeGrob(gA, gB, ncol=1)
    y <- arrangeGrob(gA, gB, ncol=1)
    grid.arrange(x, y, ncol=2)
    

    will work

    enter image description here