r - 将多面 ggplots (facet_wrap) 与 R 中的牛图对齐

标签 r ggplot2 cowplot

我正在尝试对齐由 facet_wrap 生成的两个面板图在 ggplot以下列方式(注意:面板 A 需要保持空白):

enter image description here

然而,我注意到面板 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 轴标签有关,但删除标签并不能解决问题。

问题

导致此行为的原因以及如何对齐使用 facet_wrap 生成的图,使用 cowplot包裹。

所需输出

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

enter image description here

最佳答案

就像我在评论中所说的那样,我认为这与由于 2 对 5 绘图 + Y 轴标签的差异而导致的刻面间距有关。我可能是错的(这很有可能),所以可能有一个更简单/更漂亮的解决方案。同样,这是一个建议,您可能会稍微处理一下数字,但我认为这非常接近:

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

enter image description here

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

关于r - 将多面 ggplots (facet_wrap) 与 R 中的牛图对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60362832/

相关文章:

r - 组内的组 ID

r - R 中未定义的列错误

r - 在 r 中创建类间隔并求和值

r - 使用ggplot2合并并完美对齐直方图和Boxplot

r - 结合 purrr 和 cowplot 制作绘图网格

r - str_replace "NA"的异常行为

r - 在不同层使用 ggplot2 绘制多条 ROC 曲线

r - 在R中从多边形质心到最大距离边界绘制一条线

R ggplot2字体问题

r - 不能与 cowplot 包左对齐