如何在 ggplot2 中水平对齐图形?

4

大家好,这是关于it技术的翻译。

我想要水平对齐两个使用ggplot2生成的图表。其中一个有分面(和分面条!)和图例,而另一个没有。它们共享相同的Y轴,我希望将其对齐。我可以使用它们的grobs宽度垂直对齐图表,但我无法弄清楚高度如何对齐。

以下是支持我的问题的代码片段。

library( ggplot2 )
library( gridExtra )

plot_1 <- ggplot() +
  geom_point(
    data = iris,
    aes(
      x = Petal.Length,
      y = Petal.Width,
      colour = Sepal.Length 
      ) 
    ) +
  facet_grid(
    . ~ Species 
    ) +
  theme(
    legend.position = "bottom"
    )

plot_2 <- ggplot() +
  geom_point(
    data = iris,
    aes(
      x = Sepal.Width,
      y = Petal.Width
      )
    )

g1 <- ggplotGrob( plot_1 )
g2 <- ggplotGrob( plot_2 )

# Here, how to manipulate grobs to get plot_2 scaled to the plot_1's Y axis? (ie, with an empty area right of the plot_1's legend)

grid.arrange( g1, g2, ncol = 2 )

你知道如何在使用grid.arrange()之前操纵grobs的高度吗?(欢迎任何其他建议!)此外,如何将总面积的三分之二分配给plot_1
请注意,我的实际图表实际上具有coord_flip(),但我假设它与此问题无关。
感谢您的帮助!
1个回答

1
一个简单的解决方案是创建一个空白面板:

blank<-grid.rect(gp=gpar(col="white"))

然后使用grid.arrange来创建一个两列网格,其中第二列实际上包含三行。
grid.arrange(g1, arrangeGrob(blank,g2,blank,ncol=1,
heights=c(0.2,0.9,0.2)),ncol=2) 

玩弄heights参数应该能够为我们提供所需的结果。
关于您的额外问题,grid.arrangeheightswidths参数也应该非常有用。

1
感谢您的回答Pewi!您使用“widths”参数的建议非常完美。您使用空白面板的想法很好,但输出取决于最终图形(和文件)的尺寸。我正在寻找一种更“严格”的解决方案。除了为空白面板硬编码高度之外,使用facet strip、图例和图例跳过的高度是否有帮助? - Ben
很容易将plot_2所需的数据附加到您用于plot_1的数据集中,并让facet_grid()为您完成所有对齐工作。但是,这也意味着使用grid.arrange会失去直接控制宽度的能力。 - Pewi
dat = iris; dat$Species = "All"; iris2 = rbind(dat,iris) 然后只需要在plot_1的代码中将iris替换为iris2就可以了。 - Pewi
这再次是一个好主意,但是 plot_1plot_2 不共享相同的 X 变量(以及断点、刻度标签和轴标签)。我的实际图形的 X 变量实际上具有不同的单位和跨度。facet_grid() 能够考虑到这种差异吗? - Ben

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接