首页 > 解决方案 > 组合重叠组以包含在 R 中的小提琴图/箱线图中

问题描述

我正在使用 iris 数据集处理以下代码。我想画一个小提琴图,只包括 setosa 物种,并对数据子组做一些复杂的重叠组合。

具体来说,在 x 轴上,我想首先将连续的 Sepal.Length 数据分成几组:group A=Sepal.Length < 4.7, group B=Sepal.Length 4.7 - 5, group C=Sepal.Length 5 - 5.2并且组 D=Sepal.Length > 5.2。

然后,我想在 x 轴上绘制四个小提琴/盒子,单个/重叠组:“B”、“A+C”、“D”、“A+C+D”。y 轴就是“Petal.Length”。

我还包括代码来显示每把小提琴的样本大小(n)。

我将不胜感激任何建议。谢谢你。

library(dplyr)
library(ggplot2)
library(ggpubr)
# Define order of violins on x-axis.
order <- c("B", "AC", "D", "ACD")
# Function to display sample size (n) for each violin.
give.n <- function(x){return(c(y = min(Petal.Length), label = length(x)))}
iris %>% 
  filter(Species == "setosa") %>% 
  mutate(sub_a = case_when( Sepal.Length < 4.7~"A",
                        Sepal.Length < 5~ "B",
                        Sepal.Length < 5.2~ "C",
                        TRUE~"D")) %>% 
  mutate(collapsed = c((ifelse(sub_a %in% c("A", "C"), "AC", sub_a)), (ifelse(sub_a %in% c("AC", "D"), "ACD", sub_a)))) %>% 
  ggviolin(iris[iris$Species == "setosa", ], x=collapsed, y=Petal.Length) + scale_x_discrete(limits=order) + stat_summary(fun.data = give.n, geom = "text")

编辑

请参阅下面的预期结果。请注意,每把小提琴下面的数字都是准确的。图像的其余部分只是预期结果的一个例子。

在此处输入图像描述

标签: rggplot2groupingviolin-plotggpubr

解决方案


我看不到如何将其作为单个链来执行,但这是一个蛮力解决方案,它使用cut然后bind_rows

setosa <- iris %>% filter(Species == "setosa")  %>% 
  mutate(group = cut(Sepal.Length, breaks = c(0, 4.7, 5, 5.2, Inf), labels = c("A", "B", "C", "D"), right = FALSE))

bind_rows(B = setosa %>% filter(group == "B"),
          AC =  setosa %>% filter(group %in% c("A", "C")),
          D =  setosa %>% filter(group == "D"),
          ACD = setosa %>% filter(group %in% c("A", "C", "D")),
          .id = "group2"
          ) %>% 
  mutate(group2 = factor(group2, levels = c("B", "AC", "D", "ACD"))) %>% 
  ggplot(aes(x = group2, y = Petal.Length)) + 
  geom_violin()

推荐阅读