grid_arrange_shared_legend2

The original code give the default 3 columns layout. Adding option to change this.

grid_arrange_shared_legend2 <- function(..., nrows = 1, ncols = 4) {
    plots <- list(...)
    g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
    legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
    lheight <- sum(legend$height)
    pl  <- lapply(plots, function(x) x + theme(legend.position="none"))
    tmp <- do.call(arrangeGrob, c(pl, list(ncol=ncols, nrow=nrows)))
    grid.arrange(tmp, legend, ncol=1, heights = unit.c(unit(1, "npc") - lheight, lheight))
}

Example: