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

如何将p值放置在ggpubr正负条形图的极值位置?

解决ggpubr正负条形图p值位置错乱问题

你用ggpubr绘制的正负条形图,p值位置混乱的核心原因是:默认的add_xy_position会把所有p值统一往y轴正方向放置,导致负数条形的p值被压在条形下方或位置错位。下面是修复后的代码和思路:

修复后的完整代码

library(ggpubr)
library(rstatix)
library(plyr)

# 原始数据
clust <- c(2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9)
clust <- as.factor(clust)
difference <- c(-1.62946364, -0.33442372, -1.39733564, -6.50845208, -2.51526275, -0.93206327, -0.56179492,  9.66283529, -0.01552568,  7.28771312, -3.24222047, -6.04470411,  4.09404411, -0.88665735,  5.26755900, -2.24424787)
df <- data.frame(cluster2 = clust, dif = difference)

# 绘制基础条形图
pplot <- ggbarplot(df, x = "cluster2", y = "dif",
                   fill = "cluster2",
                   palette = c("gold3","darkolivegreen3","seagreen3", "forestgreen","dodgerblue","cyan1","indianred","firebrick","brown1"),
                   rotate = TRUE,
                   add = "mean_se") +
  scale_x_discrete(limits = rev)

# 统计计算并自定义p值位置
stat_val <- df %>% 
  group_by(cluster2) %>%
  wilcox_test(dif ~ 1) %>%
  adjust_pvalue() %>%
  add_significance("p.adj") %>%
  # 合并每个组的均值和标准误数据
  left_join(df %>% 
              group_by(cluster2) %>% 
              get_summary_stats(dif, type = "mean_se"),
            by = "cluster2") %>%
  # 根据均值正负设置p值位置:正数组在均值+标准误上方加偏移,负数组在均值-标准误下方减偏移
  mutate(y.position = ifelse(mean > 0, mean + se + 0.5, mean - se - 0.5))

# 将p值添加到图中
p <- pplot + stat_pvalue_manual(stat_val, x = "cluster2", label = "p.adj.signif", y = "y.position")
p

关键调整说明

  • 放弃默认的add_xy_position自动定位,手动计算每个组的p值y坐标:正数条形的p值放在条形上方(均值+标准误+偏移量),负数条形的p值放在条形下方(均值-标准误-偏移量)。
  • 代码中的偏移量0.5可以根据你的图形尺寸自行调整,确保p值和条形之间有足够间距,避免重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 00:51:21