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

如何在R的ggpubr包ggboxplot中隐藏均值低于参照组的p值

解决ggpubr箱线图仅显示均值高于参照组的p值问题

你需要在ggpubr的ggboxplot中保留所有组的图形,但只展示均值高于参照组(ref)的组对应的显著性标记,同时不想提前过滤数据。比如示例中的lo组均值低于ref,需要隐藏它的p值标签,但保留箱线图。

核心解决方案

先筛选出均值高于参照组的组别,再针对性生成对比列表,而非让stat_compare_means自动生成所有与参照组的对比:

  • 计算每个组的均值,对比参照组均值,筛选出符合条件的组
  • 构建仅包含这些组与参照组的对比列表
  • 将该列表传给stat_compare_means的comparisons参数,同时调整标签位置

修改后的完整代码

library(ggplot2)
library(ggpubr)
library(dplyr)

# 构建原始数据
Plant<-c("ref","ref","ref","ref","ref","ref","ref","ref","ref",
         "hi","hi","hi","hi","hi","hi","hi","hi","hi",
         "lo","lo","lo","lo","lo","lo","lo","lo","lo")
Delta.CCI<-c(11.05,11.45,9.65,10.65,10.15,8.95,8.95,12.45,8.95,
             20.56,20.66,19.76,20.36,20.26,20.06,19.16,19.16,19.06,
             2.18,1.58,2.98,1.11,1.91,0.21,1.68,2.11,0.51)
df<-data.frame(Plant,Delta.CCI)

# 计算各组均值,筛选出均值高于ref的组
group_means <- df %>% 
  group_by(Plant) %>% 
  summarise(mean_val = mean(Delta.CCI), .groups = "drop")
ref_mean <- group_means$mean_val[group_means$Plant == "ref"]
target_groups <- group_means$Plant[group_means$mean_val > ref_mean]

# 生成仅包含目标组与ref的对比列表
my_comparisons <- lapply(target_groups, function(x) c("ref", x))

# 生成标签位置的交错列表(按需调整数值)
my_list <- ifelse(seq_along(target_groups) %% 2 == 0, 1, 0)

# 绘制箱线图
p<-ggboxplot(df,
             title = "A",
             x="Plant",
             y="Delta.CCI")+
  rotate_x_text(angle = 90)+
  geom_hline(yintercept = ref_mean, linetype = 2)+
  # 使用自定义对比列表,仅显示目标组的p值
  stat_compare_means(label="p.signif", label.y=my_list+28, comparisons=my_comparisons)
p

关键说明

  • 通过dplyr计算各组均值,精准筛选出需要展示p值的组,无需过滤原始数据
  • my_comparisons是自定义对比列表,传给stat_compare_means后,只会生成指定组与参照组的显著性标记
  • 所有组的箱线图完整保留,仅隐藏不符合条件组的p值标签

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:53:14