组合 ggplot2 对象时在拼凑中设置轴限制

set axes limits in patchwork when combining ggplot2 objects

当使用 patchwork 组合 ggplot2 对象时,我希望能够有一个选项,我可以轻松地为所有绘图设置一个选项,使其具有相同的 x 轴 and/or y轴范围.

代表:

library(patchwork)
library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

p1 <- mtcars %>% 
  ggplot() + 
  geom_point(aes(mpg, disp)) + 
  ggtitle('Plot 1')

p2 <- mtcars %>% 
  filter(disp < 300) %>% 
  ggplot() + 
  geom_point(aes(mpg, disp)) + 
  ggtitle('Plot 2')

p1 + p2

reprex package (v0.3.0)

于 2020 年 2 月 1 日创建

预期结果将其设置为在两个图中具有相同范围的两个轴:

library(patchwork)
library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

p1 <- mtcars %>% 
  ggplot() + 
  geom_point(aes(mpg, disp)) + 
  ggtitle('Plot 1')

p2 <- mtcars %>% 
  filter(disp < 300) %>% 
  ggplot() + 
  geom_point(aes(mpg, disp)) + 
  ggtitle('Plot 2') +
  xlim(ggplot_build(p1)$layout$panel_scales_x[[1]]$range$range) +
  ylim(ggplot_build(p1)$layout$panel_scales_y[[1]]$range$range)

p1 + p2

reprex package (v0.3.0)

于 2020 年 2 月 1 日创建

有没有人有什么想法?

好的,很抱歉回答我自己的问题,但我刚刚找到了解决方案..

这可以通过使用 & 很好地实现,它将函数应用于 patchwork 对象中的所有绘图。

1) 代表:

library(patchwork)
library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

p1 <- mtcars %>% 
  ggplot() + 
  geom_point(aes(mpg, disp)) + 
  ggtitle('Plot 1')

p2 <- mtcars %>% 
  filter(disp < 300) %>% 
  ggplot() + 
  geom_point(aes(mpg, disp)) + 
  ggtitle('Plot 2')

p_combined <- p1 + p2

p_combined

reprex package (v0.3.0)

于 2020 年 2 月 1 日创建

2) 从以下范围获取最小值和最大值:

p_ranges_x <- c(ggplot_build(p_combined[[1]])$layout$panel_scales_x[[1]]$range$range,
  ggplot_build(p_combined[[2]])$layout$panel_scales_x[[1]]$range$range)

p_ranges_y <- c(ggplot_build(p_combined[[1]])$layout$panel_scales_y[[1]]$range$range,
                ggplot_build(p_combined[[2]])$layout$panel_scales_y[[1]]$range$range)

3) 将这些范围应用于拼凑对象:

p_combined & 
  xlim(min(p_ranges_x), max(p_ranges_x)) & 
  ylim(min(p_ranges_y), max(p_ranges_y))

reprex package (v0.3.0)

于 2020 年 2 月 1 日创建

这里稍微修改一下,把上面的操作变成一个函数:

apply_consistent_y_lims <- function(this_plot){
    num_plots <- length(this_plot$layers)
    y_lims <- lapply(1:num_plots, function(x) ggplot_build(this_plot[[x]])$layout$panel_scales_y[[1]]$range$range)
    min_y <- min(unlist(y_lims))
    max_y <- max(unlist(y_lims))
    this_plot & ylim(min_y, max_y)
}