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?
You can supply nrow = 1
as a list to do.call
:
do.call(arrangeGrob, c(lapply(plots, function(x)
x + theme(legend.position="none")), list(nrow = 1)))
I adapted the example from the link you provided:
library(ggplot2)
library(gridExtra)
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, c(lapply(plots, function(x)
x + theme(legend.position="none")), list(nrow = 1))),
legend,
ncol = 1,
heights = grid::unit.c(unit(1, "npc") - lheight, lheight))
}
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(cut, price, data=dsamp, colour=clarity)
p3 <- qplot(color, price, data=dsamp, colour=clarity)
p4 <- qplot(depth, price, data=dsamp, colour=clarity)
grid_arrange_shared_legend(p1, p2, p3, p4)
here's a shorter alternative,
grid_arrange_shared_legend <- function(..., layout = rbind(c(1,2,3,4),
c(5,5,5,5))) {
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)
gl <- lapply(plots, function(x) x + theme(legend.position="none"))
grid.arrange(grobs = c(gl, list(legend)), layout_matrix = layout,
heights = grid::unit.c(unit(1, "npc") - lheight, lheight))
}