r - 组合重叠组以包含在 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")
编辑
请参阅下面的预期结果。请注意,每把小提琴下面的数字都是准确的。图像的其余部分只是预期结果的一个例子。
解决方案
我看不到如何将其作为单个链来执行,但这是一个蛮力解决方案,它使用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()
推荐阅读
- mediawiki - 如何编辑 Mediawiki 的“永恒”皮肤的右侧栏?
- html - 在同一行对齐文本和按钮
- java - hibernateTemplate.save() 命令返回主键但不保存到数据库
- swiftui - 在 SwiftUI 视图中处理 Optionals/nil 值 - 在 SwiftUI 中使用 if let
- postgresql - 只有 JOIN 在 postgres 中意味着什么?
- html - 博主移动视图上的代码格式被截断,没有滚动条选项
- ssas - 将 Model.bim 从 SQL Server 2017 转换为 2019
- azure - 如何使用 AzureRM cmdlet 删除存储帐户容器(blob),我的 power shell 版本是 5.1
- c# - `List`或`array`datastructer存储从数组c#中挑选的值?
- puppeteer - 是否可以使用 Chrome 83 版运行 Puppeteer?