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

我与影子孤独终老i 提交于 2019-12-01 18:52:57

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!