将多面 ggplots (facet_wrap) 与 R 中的 cowplot 对齐

Align facetted ggplots (facet_wrap) with cowplot in R

我正在尝试对齐两个面板图,这些面板图是通过 ggplot 中的 facet_wrap 以下列方式生成的(注意:面板 A 需要留空):

但是,我注意到面板 B 的 y 轴与面板 C 的最后一个图的 y 轴并不完全对齐(尽管两个方面都有选项 axis = 'lb')。

代码

# Load libraries
library(tidyverse)
library(cowplot)

# Create two facetted plots 
p1 <- ggplot(data = diamonds, aes(x = carat, y = price)) +
  facet_wrap(~ cut, scales = "free_y", ncol = 5) +
  geom_point(size=0.5)

p2<- ggplot(data = filter(diamonds, price < 900 & (cut == "Fair" | cut == "Good" )), aes(x = carat, y = price)) +
  facet_wrap(~ cut, scales = "free_y", ncol = 2) +
  geom_point(size=0.5)

# Create panel A and panel B
a <- plot_grid(NULL, p2, labels = c("A", "B"), axis = 'lb', ncol = 2, rel_widths = c(3,2))

# Create a combined panel of 'a' and panel C
plot_grid(a, p1, labels = c("", "C"), axis = 'lb', ncol = 1, rel_heights = c(1,1))

首先,我认为它与 y 轴标签有关,但删除标签并不能解决问题。

问题

导致此行为的原因是什么以及如何使用 cowplot 包对齐由 facet_wrap 生成的绘图。

期望输出

我希望面板 B 的 y 轴与面板 C 中最后两个图的 y 轴垂直对齐(即在红线处)

就像我在评论中所说的那样,我认为这与 2 对 5 图 + Y 轴标签的差异导致的刻面间距有关。我可能是错的(这很有可能),所以可能有一个 easier/prettier 解决方案。同样,这是一个提案,您可能会稍微玩弄一下数字,但我认为这非常接近:

# Create two facetted plots 
p1 <- ggplot(data = diamonds, aes(x = carat, y = price)) +
  facet_wrap(~ cut, scales = "free_y", ncol = 5) +
  geom_point(size=0.5)

p2<- ggplot(data = filter(diamonds, price < 900 & (cut == "Fair" | cut == "Good" )), aes(x = carat, y = price)) +
  facet_wrap(~ cut, scales = "free_y", ncol = 2) +
  geom_point(size=0.5) +
  theme(panel.spacing = unit(1.15, "lines"),
        axis.title.y = element_text(margin = margin(t = 0, r = 5, b = 0, l = 0)))

# Create panel A and panel B
a <- plot_grid(NULL, p2, labels = c("A", "B"), axis = 'lb', ncol = 2, rel_widths = c(2.985,2.015))

# Create a combined panel of 'a' and panel C
plot_grid(a, p1, labels = c("", "C"), axis = 'lb', ncol = 1, rel_heights = c(1,1))

所以基本上我添加的是你的 p2 图之间更多的间距,因为底部图中的数字比顶部的数字占用更多 space(毕竟有 2 个额外的数字)。对我来说,修复了右侧两个图的对齐方式。我还增加了标签到轴的边距。这修复了左上图的对齐方式。我不确定是否需要更改标签和轴之间的距离。