与 ggarrange 相同的 y 轴比例

时间:2021-07-27 07:50:19

标签: r ggplot2

我想使用 ggarrange 将两个图合并为一个图,并对 y 轴使用相同的缩放比例,以便更轻松地比较这些值,在我的例子中是温度计算。 这是我的示例数据:

    Sample  Group   Temperature_A   Temperature_B
1   Sample01    A   20  34
2   Sample02    B   21  31
3   Sample03    A   25  35
4   Sample04    A   18  27
5   Sample05    B   19  29
6   Sample06    A   22  32
7   Sample07    B   23  33
8   Sample08    B   17  28
9   Sample09    A   15  26
10  Sample10    B   28  39

使用以下代码,我得到以下图:

p1 <- ggplot(df, aes(Group, Temperature_A)) +
 geom_boxplot()

p2 <- ggplot(df, aes(Group, Temperature_B)) +
 geom_boxplot()

plate <- ggarrange(p1, p2, align = "hv")

plate

Sample Plot

我想要的是让他们共享他们的 y 轴,以便我可以轻松比较两种温度计算方法。我可以使用 + scale_y_continuous(limits = c(a,b)) 手动执行此操作,其中我为 a 和 b 设置了适当的值,但是,我有很多具有不同温度范围的不同数据帧。理想情况下,我会使用两个图中的最低值(+ 一些空间),并使用两个图的最高值(+ 一些空间)作为两个图的限制。有没有办法做到这一点?

我的手动方法和所需的输出:

p1 <- ggplot(df, aes(Group, Temperature_A)) +
 geom_boxplot() + 
 scale_y_continuous(limits = c(10, 40))

p2 <- ggplot(df, aes(Group, Temperature_B)) +
 geom_boxplot() + 
 scale_y_continuous(limits = c(10, 40))

plate <- ggarrange(p1, p2, align = "hv")

plate

Desiered output

2 个答案:

答案 0 :(得分:2)

这只是为了说明如何使用构面。因为你有两列温度,这被称为“宽格式”。如果您将数据重塑为长格式,则可以轻松使用分面。

library(ggplot2)

df <- read.table(text = "    Sample  Group   Temperature_A   Temperature_B
1   Sample01    A   20  34
2   Sample02    B   21  31
3   Sample03    A   25  35
4   Sample04    A   18  27
5   Sample05    B   19  29
6   Sample06    A   22  32
7   Sample07    B   23  33
8   Sample08    B   17  28
9   Sample09    A   15  26
10  Sample10    B   28  39", header = TRUE)

# Reshape
long <- tidyr::pivot_longer(
  df, c("Temperature_A", "Temperature_B"), 
  values_to = "Temperature", names_to = "Temp_name"
)

# Example of facets
ggplot(long) +
  geom_boxplot(aes(Group, Temperature)) +
  facet_wrap(~ Temp_name)

reprex package (v1.0.0) 于 2021 年 7 月 27 日创建

答案 1 :(得分:1)

我同意 teunbrand 的观点。这是一个稍微修改的方法:

  1. 以长格式导入数据
  2. 忽略异常值 outlier.shape = NA
  3. 适应 ylim
  4. facet_wrap
library(tidyverse)
df1 <- df %>% 
    pivot_longer(
        cols = starts_with("Temperature"), 
        names_to = "Temperature",
        values_to = "values"
    ) 


ggplot(df1, aes(Group, values)) +
    geom_boxplot(outlier.shape = NA) +
    coord_cartesian(ylim = c(10, 40)) +
    facet_wrap(~Temperature) + 
    theme_bw()

enter image description here

相关问题