在分面ggplot中使用stat_compare_means()实现多组t检验对比
解决方案:在分面图表中显示grouping三组的全部两两t检验对比
你遇到的问题核心是没有明确指定两两对比组合,同时统计量的位置未与点的dodge对齐,导致仅显示默认的整体检验结果。以下是修正后的代码和关键说明:
修正后的完整代码
set.seed(13) df = data.frame(grouping = c(rep("A",24),rep("B",24),rep("C",24)), id = c(rep(1,12),rep(2,12),rep(3,12),rep(4,12),rep(5,12),rep(6,12)), subject = c(rep(c("One","Two","Three","Four"),72)), family = c(rep(c("Red","Red","Red","Red","Blue","Blue","Blue","Blue","Green","Green","Green","Green"),6)), percent = sample(1:100,288,replace=T), result = "Good") library(ggplot2) library(ggpubr) library(dplyr) df %>% ggplot(aes(x=subject,y=percent, group = interaction(subject,grouping))) + geom_boxplot(outlier.shape = NA) + geom_point(aes(color = grouping),size=1.75,position = position_dodge(width = 0.75))+ scale_y_continuous(breaks = seq(0, 100, by = 25),limits = c(0,103)) + facet_grid(result~family,switch = "y") + scale_x_discrete("") + theme_minimal() + stat_compare_means(aes(group = grouping), label="p.signif", method = "t.test", paired=F, tip.length=0, step.increase = 0.1, # 增大步长避免标签重叠 comparisons = list(c("A","B"), c("A","C"), c("B","C")), # 指定所有两两对比组合 position = position_dodge(width = 0.75)) # 与点的dodge位置对齐
关键修改点说明
- 指定
comparisons参数:必须明确列出所有需要对比的组对,这是触发两两t检验的核心,否则stat_compare_means默认只会执行整体检验,因此仅显示一个"ns"结果。 - 对齐dodge位置:由于散点使用了
position_dodge(width=0.75),统计量标签需匹配相同的位置参数,否则会错位到分组中间,导致显示异常。 - 调整
step.increase:增大步长可避免三组对比的显著性标签互相重叠,让每个对比的标签分层显示。
修改后,每个分面下的每个subject分组中,都会显示A vs B、A vs C、B vs C三组的t检验显著性结果。
内容的提问来源于stack exchange,提问作者Jeff238
相关产品推荐
相关产品推荐

