Dan*_*Cee 3 testing r facet ggplot2
我有多个方面的箱线图,我想在每个方面执行 Kruskal-Wallis 测试,并将结果放在每个相应方面的左上角。
为了举例说明这一点,我使用了 iris 数据集,并向其中添加了一个名为“treatment”的附加变量。
微量元素:
library(reshape2)
library(ggplot2)
data(iris)
iris$treatment <- rep(c("A","B"), length(iris$Species)/2)
mydf <- melt(iris, measure.vars=names(iris)[1:4])
mydf$treatment <- as.factor(mydf$treatment)
mydf$variable <- factor(mydf$variable, levels=sort(levels(mydf$variable)))
ggplot(mydf,aes(x=variable, y=value)) +
geom_boxplot(aes(fill=Species)) +
facet_grid(treatment~Species, scales="free", space="free_x") +
geom_text(label=paste("Kruskal-Wallis, p=", with(mydf, kruskal.test(value ~ variable)$p.value)))
Run Code Online (Sandbox Code Playgroud)
以上是我最好的尝试,它产生了以下结果。
这显然是错误的。
我希望跨度量(Petal.Length、Petal.Width、Sepal.Length、Sepal.Width)的 Kruskal-Wallis 测试结果显示在每个面的左上角。
每个数据子集应该执行 6 次测试(根据处理和物种),所以我猜应该调整 p.value(最好由 Benjamini-Hochberg 调整)。
如果可能的话,如果每个结果 p.value 可以四舍五入到小数点后两位,那就太好了。如果可能的话,我宁愿避免使用 ggpubr,因为我在使用它时遇到问题,并坚持使用 geom_text()。谢谢!
这里给出了解决方案。
library(reshape2)
library(ggplot2)
data(iris)
iris$treatment <- rep(c("A","B"), length(iris$Species)/2)
mydf <- melt(iris, measure.vars=names(iris)[1:4])
mydf$treatment <- as.factor(mydf$treatment)
mydf$variable <- factor(mydf$variable, levels=sort(levels(mydf$variable)))
library(dplyr)
pv <- mydf %>% group_by(treatment, Species) %>%
summarize(p.value = kruskal.test(value ~ variable)$p.value)
ggplot(mydf,aes(x=variable, y=value)) +
geom_boxplot(aes(fill=Species)) +
facet_grid(treatment~Species, scales="free", space="free_x") +
geom_text(data=pv, aes(x=2, y=7, label=paste0("Kruskal-Wallis\n p=",p.value)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2507 次 |
| 最近记录: |