为每组箱线图测量值绘制 p 值

Plot p-values for each boxplots measurements in groups

我使用此数据框获取箱线图

library(reshape2)
library(ggplot2)
ID <- c("DJ45","DJ46","DJ47","DJ48","DJ49","DJ53","DJ54","DJ55","DJ56","DJ57")
Tool <- c("Tool_A", "Tool_A", "Tool_A", "Tool_A", "Tool_A", "Tool_B", "Tool_B", "Tool_B", "Tool_B", "Tool_B")
Name <- c("CMP", "CMP", "CMP", "CMP", "CMP", "CMP", "CMP", "CMP", "CMP", "CMP")
MS1 <- c(51,55,50,59,50,47,48,42,43,46)
MS2 <- c(13,11,14,11,10,17,18,17,20,21)
MS3 <- c(2,3,2,5,6,4,9,6,4,4)
MS4 <- c(16,13,14,11,16,16,18,16,19,15)
MS5 <- c(3,6,3,6,3,4,4,8,5,4)
MS6 <- c(7,7,5,5,8,9,8,6,6,9)

df1 <- data.frame(ID,Tool,Name,MS1,MS2,MS3,MS4,MS5,MS6)
df2<-melt(df1,id.var=c("ID","Tool","Name"))

p2 <- ggplot(df2, aes(x=factor(Tool),y=value,fill=factor(Tool)))+
      geom_boxplot() + labs(title="CMP") +facet_wrap(~variable)
p2

我们得到这个情节,

然后我使用 t 检验比较不同的工具,并像这样获得每次测量的 p 值。

t.test(MS1 ~ Tool, df1)
t.test(MS2 ~ Tool, df1)

我想在图中包含每个组的 p 值。我提到了 this link 但不知道如何将其编码为我的问题。请提供 inputs/direction 如何解决这个问题。

可能是因为您在初始 aes 调用中定义了 fill 导致其他解决方案失败。在这种情况下,只需将 geom_text 调用中的 fill=NA 设置为 aes

## Make pvalue data
dat <- data.frame(
    x=1.5, y=55,
    pval=sapply(split(df2, df2$variable), function(x) t.test(value ~ Tool, x)$p.value),
    variable=factor(paste0("MS", 1:6))
)

## Plot
p2 <- ggplot(df2, aes(x=factor(Tool),y=value,fill=factor(Tool)))+
  geom_boxplot() + labs(title="CMP") +
  geom_text(data=dat, aes(x=x, y=y, label=round(pval, 3), fill=NA)) +
  facet_wrap(~variable)