R: ggplot2 - Kruskal-Wallis test per facet

我们两清 提交于 2021-01-27 19:12:16

问题


I have boxplots in multiple facets and I would like to perform a Kruskal-Wallis test on each facet, and place the result on top-left of each respective facet.

To exemplify this, I am using the iris dataset, to which I added an additional variable named "treatment".

MWE:

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)))

The above is my best attempt, it produces the following.

It is obviously wrong.

I would like the result of a Kruskal-Wallis test across measures (Petal.Length, Petal.Width, Sepal.Length, Sepal.Width), to appear in top-left of each facet.

The test should be performed 6 times per each subset of data (according to treatment and Species), so I guess the p.value should be adjusted (by Benjamini-Hochberg preferably).

If possible, it would be great if each resulting p.value could be rounded to 2 decimal positions. And if possible, I'd rather avoid the use of ggpubr, cause I have problems with it, and stick to geom_text(). Thanks!


回答1:


The solution is given here.

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)))



来源:https://stackoverflow.com/questions/46536090/r-ggplot2-kruskal-wallis-test-per-facet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!