如何在不同条件下以及在不同条件下使用 ggplot 在 R 中绘制箱线图?

How to do boxplot in R with ggplot between different conditions and all through the different conditions?

我有一个包含对象名称的数据框、每个对象的值,以及包含对象类型的另一列('A'、'B'、'C' ). 类似的东西(我不能把我的数据放在这里,因为数据框太大了,但这个例子可能有帮助)

NameId 价值 类型
1 243394 一个
2 7494 B
3 243394 C
4 243394 一个
5 2437794 B
6 243 C
7 65654 C

我想绘制所有对象(这意味着 A、B 和 C 在一起)的箱线图 的对象类型 'A' 和 'B'。总共三个箱线图。 但是做 :

ggplot(data, aes(x=type, y= values))+ geom_boxplot()

显然,我得到了类型 A、B 和 C 的箱线图,但是 我想要的是一个包含所有对象的箱线图,另一个是对象类型 A,另一个是对象类型 B.

当我尝试以另一种方式进行操作时,出现错误:

Error in .check_data(data, x, y, combine = combine | merge != "none") : 
  argument "y" is missing, with no default

我也试过了:

boxplot(data$values, data$values[type=='A'],
data$values[type=='B'])

我收到另一个错误:

Error in h(simpleError(msg, call)) : 
  error in evaluating the argument 'x' in selecting a method for function 'boxplot': comparison (1) is possible only for atomic and list types

我不知道该怎么做,我想用 ggplot 而不是箱线图。 谁能帮帮我?

iris数据集为例

鸢尾包含三个物种:setosa versicolor virginica。

为了解决您的问题,我们需要使用数据集两次。

首先,使用 mutate 将物种名称重命名为“所有物种”。

其次,通过 filter.

排除了物种 'setosa'

然后我们使用union函数合并两个数据集(“所有数据”,以及不包括一组的数据)。

library(tidyverse)
iris %>% 
  mutate(Species = "All Species") %>% 
  union(iris %>% filter(Species != "setosa")) %>% 
  ggplot(aes(x=Species, y=Sepal.Length))+
  geom_boxplot()