如何在ggplot2中为汇总数据柱状图添加基于原始数据的stat_compare_means检验
解决ggplot2中stat_compare_means在facet柱状图中无效的问题
问题背景
基于原始长格式数据df,分组计算均值和标准误得到summaryFGA并绘制带误差棒的柱状图后,尝试用注释的stat_compare_means代码(指定原始df数据、采用wilcox.test方法)添加组间统计比较,但代码无效,需实现带统计标记的目标图表。
解决要点
- 修正stat_compare_means参数:
- 移除
fill=DMP美学映射,统计检验仅需x和y变量映射 - 添加
position=position_dodge(0.9),确保统计标记与柱状图位置对齐 - 确保
my_comparisons定义正确,为每个facet内的DMP组比较列表(示例:list(c("DMP组A", "DMP组B")))
- 移除
- 数据一致性检查:原始数据
df中DMP和tumor的分组需与summaryFGA完全匹配,提前清理NA值避免统计错误 - 标准误函数验证:代码中
std(FGA)若为自定义标准误计算(通常逻辑为sd(FGA)/sqrt(n())),需确保函数已正确定义;若未定义,替换为se = sd(FGA, na.rm = TRUE)/sqrt(n(), na.rm = TRUE)
修正后的完整代码
# 分组计算均值与标准误(若std未定义,替换为注释行) summaryFGA <- df %>% group_by(DMP,tumor) %>% dplyr::summarize( mean = mean(FGA, na.rm = TRUE), se = std(FGA, na.rm = TRUE) # se = sd(FGA, na.rm = TRUE)/sqrt(n(), na.rm = TRUE) # 未定义std时用此行 ) %>% as.data.frame # 定义组间比较(根据实际DMP分组调整) my_comparisons <- list(c("DMP_Group1", "DMP_Group2")) p1 <- ggplot(summaryFGA, aes(x = DMP, y = mean, fill = DMP)) + geom_bar(stat = 'identity') + geom_errorbar(aes(ymax = mean+se, ymin = mean-se), position = position_dodge(0.9), width = 0.15) + scale_fill_manual(values = jco[1:2]) + scale_color_manual(values = jco[1:2]) + ylab("Fraction of Genome Altered") + xlab("") + facet_wrap(.~tumor, nrow = 1, scales = "fixed") + # 修正后的统计检验代码 stat_compare_means( data = df, aes(x = DMP, y = FGA), comparisons = my_comparisons, method = "wilcox.test", inherit.aes = FALSE, position = position_dodge(0.9) ) + theme(axis.text.x = element_text(hjust = 1, vjust = 0.5,size = 10, angle = 90,color = "black"), axis.text.y = element_text(size = 10,color = "black"), axis.ticks = element_line(size=0.2, color="black"), axis.ticks.length = unit(0.2, "cm"), panel.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.position = "bottom", strip.text = element_text(colour = 'white', size = 10), axis.line = element_line(colour = "black")) # 自定义facet标题背景色 g <- ggplot_gtable(ggplot_build(p1)) stripr <- which(grepl('strip-t', g$layout$name)) k <- 1 for (i in stripr) { j <- which(grepl('rect', g$grobs[[i]]$grobs[[1]]$childrenOrder)) g$grobs[[i]]$grobs[[1]]$children[[j]]$gp$fill <- tumorColor[k] k <- k+1 } # 输出最终图表 grid::grid.draw(g)
内容的提问来源于stack exchange,提问作者Xiaofan Lu
相关产品推荐
相关产品推荐

