You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在分组箱线图中添加Species子组下g1与g2的Wilcoxon检验P值

在分组箱线图中添加多子组内Wilcoxon检验的P值

需求:在按Species分组的箱线图中,为每个Species子组内的g1与g2添加Wilcoxon检验的P值,现有方案无法实现多子组内两组比较。

原绘图代码

library(dplyr)
library(ggplot2)
set.seed(123)
iris$group=sample(c("g1","g2"),nrow(iris),replace = TRUE,)
ggplot(iris,aes(x=Species ,y=Sepal.Length, fill=group) )+
  geom_boxplot()

分组箱线图

原P值计算代码

L=iris %>%
  group_split(Species)
 for (i in 1:length(L)) {
   df=L[[i]]
   sub_g=unique(df$Species)
   p=df%>%
   summarise(pvalue = wilcox.test( Sepal.Length~ group,exact = FALSE)$p.value)
   print(paste0(sub_g,": ",p))
 }
#> [1] "setosa: 0.976165659102827"
#> [1] "versicolor: 0.7475079522341"
#> [1] "virginica: 0.521330527688775"

整合P值到ggplot的实现方案

方法1:用dplyr汇总P值后手动标注

通过group_by+summarise替代循环,生成包含P值和标注位置的数据框,再用geom_text添加到图中:

library(dplyr)
library(ggplot2)
set.seed(123)
iris$group <- sample(c("g1","g2"), nrow(iris), replace = TRUE)

# 计算每个Species的P值及标注位置
p_label_data <- iris %>%
  group_by(Species) %>%
  summarise(
    p_val = wilcox.test(Sepal.Length ~ group, exact = FALSE)$p.value,
    y_pos = max(Sepal.Length) + 0.2  # 调整数值控制标注在箱线图上方的高度
  )

# 绘制带P值的箱线图
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = group)) +
  geom_boxplot() +
  geom_text(
    data = p_label_data,
    aes(x = Species, y = y_pos, label = sprintf("P = %.3f", p_val)),
    inherit.aes = FALSE,  # 不继承原数据的fill映射
    size = 4
  )

方法2:用ggsignif自动添加组内比较标注

如果需要更直观的组间对比横线,可使用ggsignif包自动计算并标注:

library(dplyr)
library(ggplot2)
library(ggsignif)
set.seed(123)
iris$group <- sample(c("g1","g2"), nrow(iris), replace = TRUE)

ggplot(iris, aes(x = Species, y = Sepal.Length, fill = group)) +
  geom_boxplot() +
  geom_signif(
    comparisons = list(c("g1", "g2")),  # 指定每组内要比较的两个分组
    map_signif_level = FALSE,  # 显示具体P值而非显著性水平
    test = "wilcox.test",  # 指定检验方法
    test.args = list(exact = FALSE),  # 传递检验参数
    y_position = c(5.8, 7.2, 8.2)  # 针对每个Species设置横线位置,可根据数据调整
  )

内容的提问来源于stack exchange,提问作者Wael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:47:46