【问题标题】:Universal x axis label and legend at bottom using grid.arrange使用 grid.arrange 在底部的通用 x 轴标签和图例
【发布时间】:2014-07-18 13:50:58
【问题描述】:

我正在尝试使用 grid.arrange 绘制多个彼此相邻的图表。具体来说,我希望这些图在底部有一个共享的 x 轴标签一个图例。这是我用于安排的代码 (working example here),没有通用 x 轴:

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

图例是一个 TableGrob 对象;通用 x 轴应该是沿

行的 textGrob
bottom=textGrob("X Axis")

但是,如果我将其添加到代码中,则图例将移至右侧。如果我指出图例和标签都应该在底部,其中一个仍会移动到右侧。那么问题来了,有没有办法将通用 x 轴标签与底部的图例结合起来?

【问题讨论】:

  • 令人困惑的是,我认为底部标签称为“sub”,而不是“bottom”
  • 标签已在 v2.0.0 中更新:现在是顶部、底部、左侧、右侧。

标签: r plot ggplot2 gridextra grob


【解决方案1】:

有一个类似的问题,所以我想出了这样的东西。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    相关资源
    最近更新 更多