【问题标题】:Plot alignment does not work for height and width simultaneously in plot_grid在 plot_grid 中,绘图对齐不适用于高度和宽度
【发布时间】:2022-01-05 16:22:17
【问题描述】:

以下代码生成如下图所示的网格:

library(tidyverse)
library(cowplot)

p1 <- cars %>%
  ggplot(aes(x = speed, y = dist)) +
  geom_point() +
  theme_bw()


p2 <- cars %>%
  ggplot(aes(x = speed, y = dist)) +
  geom_point() +
  scale_y_continuous(trans = "log2", breaks = c(2, 4, 8, 16, 32, 64, 128), 
                     limits = c(2, 128)) +
  annotation_logticks(sides = "l") +
  theme_bw()


p3 <- diamonds %>% 
  ggplot(aes(x = carat, y = price, colour = clarity)) +
  geom_point() +
  theme_bw() +
  theme(legend.position = c(0.8, 0.4))


p4 <- plot_grid(p1, p1, nrow = 2, labels = c("B", "C"))


p5 <- plot_grid(p3, p4, nrow = 2, align = "hv", axis = "lb", rel_heights = c(0.5, 1), 
                labels = c("A", ""))

p6 <- plot_grid(p1, p2, nrow = 2, align = "h", rel_heights = c(0.5, 1), 
                labels = c("D", "E"))


p7 <- plot_grid(p5, p6, ncol = 2, align = "b")

p7

我希望将(A)的底轴与(B,C)的顶轴分别对齐,并将(C)的底轴与(E)的底轴对齐。这应该在 (E) 的高度和 (A) 的宽度上拉伸 (B,C) 网格图。我尝试了几种对齐方式。

我发现queries 与此问题类似,它允许正确对齐宽度或高度,但不能同时对齐!

我还要补充一点,这个可重现的例子是我能得到的最接近我的实际情节的例子。在这里,我设法将宽度与面板 (A) 对齐,但无法将 (B,C) 的高度与 (E) 对齐。

【问题讨论】:

    标签: ggplot2 cowplot


    【解决方案1】:

    我可以建议使用拼凑而成吗?我发现它比其他任何东西都更优雅地处理面板的对齐。

    library(tidyverse)
    library(cowplot)
    
    p1 <- cars %>%
      ggplot(aes(x = speed, y = dist)) +
      geom_point() +
      theme_bw()
    
    
    p2 <- cars %>%
      ggplot(aes(x = speed, y = dist)) +
      geom_point() +
      scale_y_continuous(trans = "log2", breaks = c(2, 4, 8, 16, 32, 64, 128), 
                         limits = c(2, 128)) +
      annotation_logticks(sides = "l") +
      theme_bw()
    
    
    p3 <- diamonds %>% 
      ggplot(aes(x = carat, y = price, colour = clarity)) +
      geom_point() +
      theme_bw() +
      theme(legend.position = c(0.8, 0.4))
    
    library(patchwork)
    #> 
    #> Attaching package: 'patchwork'
    #> The following object is masked from 'package:cowplot':
    #> 
    #>     align_plots
    
    p3 + p1 + p1 + p1 + p2 +
      plot_layout(
        design = "
        AD
        BE
        CE
        "
      ) +
      plot_annotation(tag_levels = "A")
    

    由reprex package 创建于 2022-01-05 (v2.0.1)

    【讨论】:

    • 这个解决方案很神奇!非常感谢。
    猜你喜欢
    • 2016-09-11
    • 1970-01-01
    • 2011-01-30
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 2020-06-03
    • 1970-01-01
    相关资源
    最近更新 更多