Manasi Shah
Manasi Shah

Reputation: 437

common legend to the right of ggplot

I would like to align a common legend to the right of the plot instead of bottom. A similar example is discussed at here (Second answer by Stevenson)

With basic edits to the code by Stevenson, I changed the legend.position to right, if I keep the ncol=1 then the legend still appears at bottom, but if I edit ncol=2 the legend appears on the right but there is a huge space between the legend and the plot.

library(ggplot2)
library(gridExtra)

grid_arrange_shared_legend <- function(...) {
plots <- list(...)
g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$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 = 2,
heights = 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)

How can I have the legend properly stacked next to the plot? I have looked at a few posts but none have actually addressed aligning the legend in a multi-plot to the right.

Appreciate the help, thanks!

Upvotes: 2

Views: 988

Answers (1)

baptiste
baptiste

Reputation: 77096

you want to adjust widths, not heights

grid_arrange_shared_legend <- function(...) {
  plots <- list(...)
  g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$grobs
  legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
  lw <- sum(legend$width)
  gl <- lapply(plots, function(x) x + theme(legend.position="none"))
  grid.arrange(arrangeGrob(grobs = gl), legend,
    ncol = 2, widths = unit.c(unit(1, "npc") - lw, lw))
}

Upvotes: 3

Related Questions