Here is a function to extract the legend from a ggplot2 object and use it as a own object in grid.arrange()
:
https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
However, what i am really struggling with: I want the plots in only one row, but apparently the plot layout is not changeable. I believe that
grid_arrange_shared_legend <- function(...) {
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)
grid.arrange(
do.call(arrangeGrob, lapply(plots, function(x)
x + theme(legend.position="none"))),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight))
}
needs a nested grid.arrange command, as the ncol=1
argument is related to the legend. Is there a way to to do this?
here's a shorter alternative,
You can supply
nrow = 1
as a list todo.call
:I adapted the example from the link you provided: