简体   繁体   English

如果我已经在使用构面并且不能再次使用它们,则与 ggarrange 的 y 轴范围相同

[英]Same y-axis range with ggarrange if I am already using facets and cannot use them again

my question is basically a follow-up to this question .我的问题基本上是这个问题的后续问题 However, the problem is that in the said question the answer completely bypasses the fact that ggarrange is used and instead transfers the whole issue to be handled by the facets functionality of ggplot.然而,问题在于,在上述问题中,答案完全绕过了使用ggarrange的事实,而是将整个问题转移到 ggplot 的方面功能来处理。

This doesn't work for me since I already am using facets in the sub-plots and I cannot use them again.这对我不起作用,因为我已经在子图中使用了构面,而且我不能再次使用它们。

Here is some example code.这是一些示例代码。 I am wondering how to achieve that the two plots which are joined with ggarrange have the same range of y-axis (of course, not setting the limits manually).我想知道如何实现与 ggarrange 连接的两个图具有相同的 y 轴范围(当然,不是手动设置限制)。

mtcars %>% 
  group_split(vs) %>% 
  map(~ggplot(., aes(x = mpg, y = wt)) +
        geom_point() +
        facet_grid(rows = vars(am), cols = vars(gear))) %>% 
  ggarrange(plotlist = .)

在此处输入图像描述

As you can see, the left image's y-axis ranges from 2 to 5, while the right plot's y-axis ranges from 1.5 to 3.5.如您所见,左图的 y 轴范围为 2 到 5,而右图的 y 轴范围为 1.5 到 3.5。 How can I make them be the same?我怎样才能使它们相同?

I'm once again arguing for abandoning the 'ggarrange' approach, this time in favour of the {patchwork} package, which allows you to apply an operation to all previous plots.我再次主张放弃 'ggarrange' 方法,这次支持 {patchwork} package,它允许您对之前的所有绘图应用操作。 In this case, we can use & scale_y_continuous(limits =...) to set the limits for all plots.在这种情况下,我们可以使用& scale_y_continuous(limits =...)来设置所有图的限制。

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

mtcars %>% 
  group_split(vs) %>% 
  map(~ggplot(., aes(x = mpg, y = wt)) +
        geom_point() +
        facet_grid(rows = vars(am), cols = vars(gear))) %>% 
  wrap_plots() &
  scale_y_continuous(limits = range(mtcars$wt))

Created on 2022-12-08 by the reprex package (v2.0.0)reprex package (v2.0.0) 创建于 2022-12-08

One option would be to compute and add the range of your x and y variables to your dataset before splitting, which could then be used to set the limits.一种选择是在拆分之前计算 x 和 y 变量的范围并将其添加到数据集中,然后可以使用它来设置限制。

library(dplyr)
library(ggplot2)
library(ggpubr)
library(purrr)

mtcars %>% 
  mutate(across(c(mpg, wt), list(range = ~list(range(.x))))) %>%
  group_split(vs) %>% 
  map(~ggplot(., aes(x = mpg, y = wt)) +
        geom_point() +
        scale_x_continuous(limits = .$mpg_range[[1]]) +
        scale_y_continuous(limits = .$wt_range[[1]]) +
        facet_grid(rows = vars(am), cols = vars(gear))) %>% 
  ggarrange(plotlist = .)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM