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

如何在R语言ggplot分面条形图的指定柱子上方添加显著性星号*

解决ggplot分面条形图指定位置加显著性星号的方案

核心逻辑为单独构建仅包含需要标注星号行的标注数据集,配合geom_text的position_dodge参数对齐柱子位置,不会出现全图加星号或者图形变形的问题。

完整可运行代码如下:

# 加载所需包
library(ggplot2)

# 构造原始数据
Treatment <- rep(c("Treatment A","Treatment A","Treatment B","Treatment B"), 3)
Group <- c(rep(c("A. Paired cohort"), 4),rep(c("B. Low cohort"), 4),rep(c("C. Normal cohort"), 4))
Outcome <- rep(c("Outcome P","Outcome D"),6)
Percent <- c(6.7,3.3,22.6,16.1,4.9,2.4,25,15,8.2,4.1,20.8,17)
df <- data.frame(Treatment,Group,Outcome,Percent)

# 保留Outcome原始顺序,修正原代码缺失的右括号
df$Outcome <- factor(df$Outcome, levels = unique(df$Outcome))

# 构造标注数据集,仅保留需要加星号的行
label_df <- df[
  (df$Group == "A. Paired cohort" & df$Treatment %in% c("Treatment A", "Treatment B")) |
    (df$Group == "B. Low cohort" & df$Treatment == "Treatment A"),
]
# 设置星号显示的y坐标,比柱子顶端高2个单位,避免遮挡
label_df$label_y <- label_df$Percent + 2
# 标注内容为星号
label_df$sig_label <- "*"

# 绘制图形
ggplot(df, aes(x=Outcome, y=Percent)) +
  geom_bar(aes(fill=Treatment),stat="identity", position="dodge")+
  # 加星号图层,dodge宽度和条形图一致保证对齐
  geom_text(
    data = label_df,
    aes(y = label_y, label = sig_label),
    position = position_dodge(width = 0.9),
    size = 8
  ) +
  theme_classic() +
  scale_fill_grey() +
  xlab("") + ylab("%") +
  facet_wrap(~Group) +
  ylim(0,40)

可调整参数说明:

  • 如需调整星号垂直位置,可修改label_y的偏移量(代码中的+2),数值越大星号位置越高
  • 星号大小可通过geom_text的size参数调整
  • 后续需要增减标注的柱子,只要修改label_df的筛选条件即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:15:04