合并重叠组以包含在 R 中的 violin plot/box plot 中

Combining overlapping groups to include in violin plot/box plot in R

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

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

然后,我想在 x 轴上绘制四个 violins/boxes,single/overlapping 组:"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")

编辑

请参阅下文了解预期结果。请注意,每把小提琴下方的数字都是准确的。图片的其余部分只是预期结果的示例。

我看不出如何将其作为单链执行,但这里有一个 brute-force 解决方案,它使用 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()