首页 > 解决方案 > 定义要在箱线图中绘制的箱/子组(来自连续变量)(R中的ggplot)

问题描述

以 iris 数据集为例,我想Sepal.Length在 x 轴和Petal.Lengthy 轴上绘制一个箱线图(仅适用于 setosa 物种)。然而,这首先需要将 x 轴的连续Sepal.Length数据分组:Sepal.Length < 4.7, Sepal.Length 4.7 - 5, Sepal.Length 5 - 5.2 and Sepal.Length > 5.2.其次,它需要将第一组和第三组分组在一起。我尝试了下面的代码,但这不起作用。任何建议,将不胜感激。谢谢你。

library(ggplot2)
bin1 <- iris[iris$Sepal.Length < 4.7, ]
bin2 <- iris[iris$Sepal.Length >=4.7 & <5, ]
bin3 <- iris[iris$Sepal.Length >=5 & <5.2, ]
bin4 <- iris[iris$Sepal.Length >=5.2, ]
binA <- bin1 + bin3
order <- c(bin2, binA, bin4)
ggboxplot(iris[iris$Species == "setosa", ], x="Sepal.Length", y="Petal.Length") + scale_x_discrete(limits=order)

标签: rggplot2

解决方案


我会使用该cut功能来做你正在做的事情。之后,您可以使用fct_collapse修改您的切割点。您可以执行以下操作:

library(dplyr)
library(forcats)
library(ggplot2)

iris %>% 
  filter(Species == "setosa") %>% 
  mutate(sub_species = cut(Sepal.Length, breaks = c(-Inf, 4.7, 5, 5.2, Inf))) %>% 
  mutate(sub_species = fct_collapse(sub_species,
                                    combined = c("(-Inf,4.7]", "(5.2, Inf]"))) %>% 
  ggplot(aes(sub_species, Petal.Length))+
  geom_boxplot()

这会给你想要的。

或者,您可以替换cut函数并使用dplyr's case when 函数看起来像:

iris %>% 
  filter(Species == "setosa") %>% 
  # Case when to cases
  mutate(sub_a = case_when( Sepal.Length < 4.7~"A",
                            Sepal.Length < 5~ "B",
                            Sepal.Length < 5.2~ "C",
                            TRUE~"D")) %>% 
  # Collapse A and D
  mutate(collapsed = ifelse(sub_a %in% c("A", "D"), "combined", sub_a)) %>% 
  ggplot(aes(collapsed, Petal.Length))+
  geom_boxplot()

在 OP 评论中,问题被扩展为包括创建其他几个子类。为了解决这个问题,我将使用该mutate函数创建一些额外的子类别,然后使用该gather函数将它们全部拉到一个列中,同时保留每个子类中的数据(例如保持计数正确)。

iris %>% 
  filter(Species == "setosa") %>% 
  # Case when to cases
  mutate(sub_a = case_when( Sepal.Length < 4.7~"A",
                            Sepal.Length < 5~ "B",
                            Sepal.Length < 5.2~ "C",
                            TRUE~"D")) %>% 
  # Collapse A and D
  mutate(collapsed1 = ifelse(sub_a %in% c("A", "C"), "A+C", sub_a)) %>% 
  mutate(collapsed2 = ifelse(sub_a %in% c("A", "C", "D"), "A+C+D", sub_a)) %>% 
  # Pull all the new categories together into a new column called subclass
  gather(new_cat, subclass, sub_a:collapsed2) %>% 
  # Filter to desired
  filter(subclass %in% c("B", "A+C", "D", "A+C+D")) %>% 
  ggplot(aes(subclass, Petal.Length))+
  geom_boxplot()


推荐阅读