如何在同一个图中创建两个 ggplot 箱线图?

How to create two ggplot boxplots in the same figure?

我在 R 中有一个数据集,其中包含 6 个定量变量和另一个二进制变量。我的 objective 是,对于每个定量变量,创建一个箱线图来比较这个变量的值对于二进制变量的两个级别,我希望使用 ggplot 将 6 个图像放入 R 中的单个图形中.

考虑以下示例来说明我在说什么。到目前为止,我知道如何使用 R:

中的默认 "boxplot" 函数来解决这个问题
X = data.frame(a = c(rep("T", 5), rep("F", 5)), 
               b = rnorm(10), 
               c = runif(10))

par(mfrow = c(1, 2))
boxplot(b ~ a, data = X)
boxplot(c ~ a, data = X)

而且我知道如何使用 ggplot 创建我想要的两个箱线图:

library(ggplot2)

ggplot(X, aes(x = a, y = b)) + 
  geom_boxplot(aes(fill = a))
ggplot(X, aes(x = a, y = c)) + 
  geom_boxplot(aes(fill = a))

我不知道如何将两个 ggplot 箱线图显示为一个图形。

这是你需要的吗?我认为 用 "id" 比 更好。 编辑:最终答案

X %>% 
  gather("id","value",2:3) %>% 
  group_by(id) %>% 
  ggplot(aes(a,value,fill=id))+geom_boxplot()+facet_wrap(~id)

原文:

答案:如果你想填一个,那么:

X %>% 
  gather("id","value",2:3) %>% 
  group_by(id) %>% 
  ggplot(aes(id,value))+geom_boxplot(aes(fill=a))

否则:

 library(tidyverse)
    X %>% 
      gather("id","value",2:3) %>% 
      group_by(id) %>% 
      ggplot(aes(a,value,fill=id))+geom_boxplot()