ggplot2 grid_arrange_shared_legend share axis labels

1.5k Views Asked by At

I am using grid_arrange_shared_legend to combine plots with the same legend into one plot with one legend. Is there a way to edit the function slightly so it also shares the x and y axis labels? For example, if I made 3 graphs and wanted a 3x1 grid of those graphs made with grid_arrange_shared_legend, and wanted the shared x axis label on the very bottom and the shared y axis label on the left, how would I do that? This is the code I am using for the function:

grid_arrange_shared_legend <- function(..., ncol=1, mytitle="mytitle") {
  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(ncol=ncol, lapply(plots, function(x)
      x + theme(legend.position="none")))),
    legend,
    ncol = 1,
    heights = unit.c(unit(.95, "npc") - lheight, lheight),
    top=textGrob(mytitle,  gp = gpar(fontsize=16)))

}
1

There are 1 best solutions below

0
On

I had the same problem.

My solution was to add a blank x-axis title to each plot (to save space to add an axis title):

p1 <- p1 + xlab(" ")

and then having created the plots with shared legends:

grid_arrange_shared_legend(p1, p2, p3, position = "right")

I then added new text as a new axis title:

grid.text("My title", y= 0.02, x=0.43)