2017-10-03 11 views
1

나는 여러 패싯에 박스 플롯을 가지고 있으며 각 패싯에서 Kruskal-Wallis 테스트를 수행하고 결과를 각 패싯의 왼쪽 위에 배치하고 싶습니다.R : ggplot2 - 패싯 당 Kruskal-Wallis 테스트

예를 들어 홍채 데이터 세트를 사용하고 있는데 여기에 "치료"라는 추가 변수를 추가했습니다.

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

위의 최선을 시도, 그것은 다음을 생산하고있다.

test

그것은 분명히 잘못된 것입니다.

각 패싯의 왼쪽 상단에 측정 값 (Petal.Length, Petal.Width, Sepal.Length, Sepal.Width)에 대한 Kruskal-Wallis 테스트 결과가 나타나기를 바랍니다.

테스트는 데이터의 각 하위 집합당 6 회 수행해야하므로 (처리 및 종에 따라) p.value를 조정해야합니다 (Benjamini-Hochberg 기준).

가능한 경우 각 결과 p.value를 소수점 둘째 자리로 반올림 할 수 있으면 좋을 것입니다. 가능하다면 ggpubr을 사용하지 말고 문제가 생겨 geom_text()를 사용하십시오. 감사!

답변

2

용액은 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))) 

enter image description here

+0

이것은 덕분입니다! 이 경우 여러 개의 테스트를 위해 p- 값을 조정해야합니까? – DaniCee

+0

@DaniCee p- 값을 조정하거나 조정하지 않기 전에이 보고서를 읽는 것이 좋습니다. http://www.jclinepi.com/article/S0895-4356(00)00314-0/fulltext –