ggplot分组柱状图添加指定组间显著性星号标记实现方法
失败原因
geom_signif和ggpubr的显著性标注函数默认适配单分组x轴结构,你的图表是双分组dodge柱状图:x轴主分类为年龄组,柱体按奖励条件做位置偏移,函数无法自动识别偏移后的柱体坐标,因此标注错位或无法正常渲染。
实现方法
直接手动指定dodge后每个柱体的实际x坐标,用geom_signif的手动标注模式添加标记即可,不需要做复杂的统计映射:
- 两个年龄组的x轴基准位置:Young Adult在x=1,Older Adult在x=2
- 你设置的
position_dodge宽度为0.6,4个奖励条件柱体在每个年龄组下从左到右的偏移量为-0.225、-0.075、0.075、0.225,对应实际x坐标可直接计算得到 - 仅给Young Adult组Self High Value和Self Low Value的比较对标注
**,其余相邻柱体比较统一标注ns
完整可运行代码
library(tidyverse) library(ggsignif) viz_data_one <- tibble( age_group = c(rep("Young Adult", 4), rep("Older Adult", 4)), MemoryAccuracy = c(32.8, 28.448, 27.672, 27.075, 29.667, 28.944, 27.556, 28.889), upper = MemoryAccuracy + 1.76, lower = MemoryAccuracy - 1.76, reward = rep(c("Self High Value", "Self Low Value", "Other High Value", "Other Low Value"), 2) ) %>% mutate( reward = as_factor(reward) %>% fct_relevel("Self High Value", "Self Low Value", "Other High Value", "Other Low Value")) viz_data_one <- viz_data_one %>% mutate(upper = MemoryAccuracy + ifelse(age_group == "Young Adult", 1.76, 1.94), lower = MemoryAccuracy - ifelse(age_group == "Young Adult", 1.76, 1.94)) p <- viz_data_one %>% ggplot(aes(x = age_group, y = MemoryAccuracy, fill = reward, ymin = lower, ymax = upper)) + geom_col(width = .5, position = position_dodge(.6), color = "black", key_glyph = "polygon") + geom_errorbar(width = .1, position = position_dodge(.6)) + # 显著性标注层 geom_signif( xmin = c(0.775, 0.925, 1.075, 1.775, 1.925, 2.075), xmax = c(0.925, 1.075, 1.225, 1.925, 2.075, 2.225), y_position = c(35.5, 34.5, 34.5, 32.5, 31.5, 31.5), annotation = c("**", "ns", "ns", "ns", "ns", "ns"), tip_length = 0.01, size = 0.5, textsize = 5, manual = TRUE ) + scale_fill_manual(values = c("#E495A5", "#ABB065", "#39BEB1", "#ACA4E2" )) + labs( x = "Age Group", y = "Memory Accuracy (%)", fill = NULL, title = "" ) + theme( plot.margin = unit(c(1, 1, 1, 1), "cm"), panel.background = element_blank(), plot.title = element_text(size = 14, face = "bold", hjust = 0.5, margin = margin(b = 15)), axis.line = element_line(color = "black"), axis.title = element_text(size = 14, color = "black", face = "bold"), axis.text = element_text(size = 18, color = "black"), axis.text.x = element_text(margin = margin(t = 10)), axis.text.y = element_text(size = 14), axis.title.y = element_text(margin = margin(r = 10)), axis.ticks.x = element_blank(), legend.position = c(0.90, 0.99), legend.background = element_rect(color = "black"), legend.text = element_text(size = 15), legend.margin = margin(t = 5, l = 5, r = 5, b = 5), legend.key = element_rect(color = NA, fill = NA) ) + guides( fill = guide_legend( keywidth = .5, keyheight = .5, default.unit= "cm" ) ) p + expand_limits(y = 38)
参数调整说明
- 运行前需先安装依赖:执行
install.packages("ggsignif")即可 - 若标注高度不合适,直接修改
y_position向量内的数值,数值越大标注位置越靠上 tip_length控制显著性横线两端的短竖线长度,textsize控制标注文字大小,size控制横线粗细- 若要增减比较对,同步增删
xmin/xmax/y_position/annotation四个参数的元素即可,四个向量长度必须保持一致
内容的提问来源于stack exchange,提问作者Tessa
相关产品推荐
相关产品推荐

