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

为分面箱线图添加组内两两比较的P值/显著性标记

在ggplot2分面箱线图中实现分面内组间两两显著性标注

问题分析

你之前的代码里,stat_compare_means默认对全局所有组进行比较,而非每个分面(method)内的组,导致结果不符合预期;使用stat_pvalue_manual报错则是因为没有正确生成符合要求的统计结果对象。

解决步骤

  1. 提前计算分面内的两两比较统计量
    用rstatix包按分面分组计算组间两两比较的p值,同时自动生成标注所需的坐标位置:

    library(tidyverse)
    library(ggpubr)
    library(rstatix)
    
    # 读取数据
    df <- read_csv("data.csv")
    
    # 按method分组,计算crop间的两两t检验(非参数可换pairwise_wilcox_test)
    stat_test <- df %>%
      group_by(method) %>%
      pairwise_t_test(H ~ crop, p.adjust.method = "bonferroni") %>%
      add_xy_position(x = "crop") # 自动计算标注的xy位置
    
  2. 绘图并标注显著性
    用stat_pvalue_manual加载提前计算好的统计结果,实现分面内的精准标注:

    df %>%
      ggplot(aes(crop, H, fill = crop)) +
      geom_boxplot() +
      labs(x = "", y = "Shannon Index per field") +
      scale_fill_manual(
        values = c(
          "antiquewhite4", "burlywood4", "cornsilk2",
          "cornsilk", "antiquewhite3", "antiquewhite2"
        )
      ) +
      facet_wrap(~method, scales = "free_x") +
      stat_pvalue_manual(stat_test, label = "p.signif", tip.length = 0.01)
    

关键说明

  • 若数据不符合t检验前提,可将pairwise_t_test替换为pairwise_wilcox_test(非参数检验)。
  • p.adjust.method参数可根据需求调整多重比较校正方法,比如"holm"、"fdr"等。
  • tip.length控制显著性标注线段的长度,可根据图表美观度调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 01:52:33