2

I am using grid_arrange_shared_legend, which I found here to generate a grid of plots. I slightly modified grid_arrange_shared_legend to fit my needs:

grid_arrange_shared_legend <- function(plots) {
  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))
}

I call this function like that

pdf("plots.pdf",width=12.21/2.54, height=20.92/2.54)
grid_arrange_shared_legend(plotList) #ncol=length(ns), main = "Main title")
dev.off()

This generates a pdf file with 4 columns of plots (see pdf1). However, I need 3 columns instead. I tried achieving this by replacing ncol=1 with ncol=3 in grid_arrange_shared_legend. This results in all the plots being in the left column and the middle and right column being empty (see pdf2).

How can I achieve a 3 column plot?

Julian Karch
  • 444
  • 4
  • 20
  • [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – shekeine Oct 21 '15 at 10:40
  • 1
    That `ncol=1` is to put the plots and legend in one column. To arrange the plots themselves you need to pass a `ncol` argument to the `arrangeGrob.`.. so change that part to `do.call(arrangeGrob, c(lapply(plots, function(x) x + theme(legend.position="none")), ncol=3))` – user20650 Oct 21 '15 at 11:09

1 Answers1

1

Changing grid_arrange_shared_legend to

grid_arrange_shared_legend <- function(plots) {
  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(arrangeGrob(grobs=lapply(plots, function(x)
      x + theme(legend.position="none")),ncol = 3),
    legend,
    ncol = 1,
    heights = unit.c(unit(1, "npc") - lheight, lheight))
}

solved the issue. user20650 provided this solution in his comment.

Julian Karch
  • 444
  • 4
  • 20