ggplot2 grid_arrange_shared_legend share axis labels
Asked Answered
L

1

0

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)))

}
Lymanlymann answered 13/9, 2017 at 15:12 Comment(2)
why not use ?facet_grid()Teniers
you could suppress the x/y-axis titles and then use the bottom & left argument in grid.arrange o or use faceting as suggested ^^Mastoidectomy
M
0

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)
Mardis answered 12/7, 2019 at 13:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.