0

我有两个facet_wrap要垂直组合的图,并与拼凑而成左对齐。我的问题是两个图之间的列数不相等(如下面的简单示例所示)。

有没有办法让这些图左对齐拼凑?

library(ggplot2)
library(dplyr)
library(purrr)
library(patchwork)

plot_ls <- data.frame(var_a = c(rep(1, 5), rep(2, 4)),
                 var_b = c(letters[1:5], letters[c(1:2, 4:5)]),
                 var_x = "a",
                 var_y = rnorm(9),
                 var_color = "b") %>%
  split(.$var_a) %>%
  imap(function(df.x, var_a.x) {
    ggplot(data = df.x) +
      geom_point(aes(x = var_x, y = var_y, color = var_color)) +
      facet_wrap(var_b ~ ., scales = "free", nrow = 2) +
      ylab(var_a.x) +
      theme(aspect.ratio = 1,
            axis.title.x = element_blank(),
            plot.margin = margin(1,1,1,1))
  })

# ...centered, not aligned to the left...
plot_ls[[1]] + plot_ls[[2]] +
         plot_layout(ncol = 1,
                     guides = 'collect') & 
         theme(legend.position = 'bottom')
4

1 回答 1

0

问题可能与想要设置有关aspect.ratio = 1,如果我还想控制对齐和尺寸,拼凑可能无法实现。我可以通过删除左对齐aspect.ratio = 1并通过调整设计来获得接近对齐的方面(根据@RichardTelford 的评论):

plot_ls <- data.frame(var_a = c(rep(1, 5), rep(2, 4)),
                 var_b = c(letters[1:5], letters[c(1:2, 4:5)]),
                 var_x = "a",
                 var_y = rnorm(9),
                 var_color = "b") %>%
  split(.$var_a) %>%
  imap(function(df.x, var_a.x) {
    ggplot(data = df.x) +
      geom_point(aes(x = var_x, y = var_y, color = var_color)) +
      facet_wrap(var_b ~ ., scales = "free", nrow = 2) +
      ylab(var_a.x) +
      theme(# aspect.ratio = 1,
            axis.title.x = element_blank(),
            plot.margin = margin(1,1,1,1))
  })

# ...centered, not aligned to the left...
plot_ls[[1]] + plot_ls[[2]] +
         plot_layout(design = "
                         AAAAAA
                         BBBB##
                         ",
                     guides = 'collect') & 
         theme(legend.position = 'bottom')
于 2021-09-11T15:18:50.760 回答