Universal x axis label and legend at bottom using grid.arrange
Asked Answered
B

1

5

I am trying to plot a number of graphs next to each other using grid.arrange. Specifically, I would like the plots to have a shared x axis label and a legend at the bottom. Here is the code I am using for the arrangement (working example here), sans the universal x axis:

plot.c <- grid.arrange(arrangeGrob(plot.3 + 
                                 theme(legend.position="none"),
                               plot.2 + theme(legend.position="none"),
                               plot.4 + theme(legend.position="none"),
                               nrow=1),
                   my.legend, 
                   main="Title goes here", 
                   left=textGrob("Y Axis", rot = 90, vjust = 1),
                   nrow=2,heights=c(10, 1))

The legend is a TableGrob object; the universal x axis should be a textGrob along the lines of

bottom=textGrob("X Axis")

However, if I add that to the code, the legend is moved to the right side. If I indicate that both legend and label should be at the bottom, one of them still moves to the right side. Thus the question, is there a way of combining a universal x axis label with a legend at the bottom?

Boomerang answered 18/7, 2014 at 13:50 Comment(2)
confusingly, i think the bottom label is called "sub", not "bottom"Due
the labels have been updated in v2.0.0: it's now top, bottom, left, right.Due
T
9

Had a similar issue so I came up with something like this.

library(ggplot2)
library(gtable)
library(gridExtra)

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(price, carat, data=dsamp, colour=clarity) + theme(legend.position="none") + xlab("")
p2 <- qplot(price, cut, data=dsamp, colour=clarity) + theme(legend.position="none") + xlab("")
p3 <- qplot(price, color, data=dsamp, colour=clarity) + theme(legend.position="none") + xlab("")
p4 <- qplot(price, depth, data=dsamp, colour=clarity) + theme(legend.position="none") + xlab("")

legend <- gtable_filter(ggplot_gtable(ggplot_build(p1 + theme(legend.position="bottom"))), "guide-box")
lheight <- sum(legend$height)
p <- arrangeGrob(p1, p2, p3, p4, ncol=2)
theight <- unit(12, "points")
p <- arrangeGrob(p, textGrob("price", gp=gpar(fontsize=12)), heights=unit.c(unit(1, "npc") - theight, theight))
p <- arrangeGrob(p, legend, heights=unit.c(unit(1, "npc") - lheight, lheight), ncol=1)
print(p)

enter image description here

Takeover answered 17/4, 2015 at 3:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.