如何在箱线图中展示双因素ANOVA的紧凑字母显示(CLD)
双因素ANOVA箱线图CLD字母对应分组问题
问题背景
使用multcompLetters4()函数获取4组数据双因素ANOVA的紧凑字母显示(CLD)后,绘制带字母的箱线图时,geom_text()无法区分不同的Tx分组,字母全部显示在同一Group位置,无法对应到各自的填充组。
原始数据与代码
数据
data1 <- structure(list(Tx = c("T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "T", "T", "T", "T", "T", "T", "T", "T", "T", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E"), Group = c("I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G" ), Nb = c(24, 21, 13, 18, 11, 12, 10, 17, 22, 13, 3, 6, 12, 11, 1, 5, 10, 10, 10, 2, 18, 15, 15, 16, 19, 16, 22, 23, 19, 11, 10, 11, 16, 5, 15, 14, 14, 17, 16)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -39L))
原始绘图代码
aov1 <- aov(Nb~Tx*Group, data=data1) tukey <- TukeyHSD(aov1) tukey.cld <- multcompLetters4(aov1, tukey) cld <- as.data.frame.list(tukey.cld$`Tx:Group`) cld summary <- data1 %>% group_by(Tx,Group) %>% summarise( w=mean(Nb), sd=sd(Nb), max=max(Nb)) %>% arrange(desc(w)) summary$Tukey <- cld$Letters ggplot(data1, aes(x = Group, y = Nb, fill = Tx)) + geom_boxplot(show.legend = TRUE, outlier.shape = NA) + geom_text(data = summary, aes(x = Group, label = Tukey, y = max), inherit.aes = FALSE)
解决方法
核心是让文本位置与箱线图的分组偏移匹配,使用position_dodge()对齐不同Tx分组的字母,同时确保分组逻辑一致:
修改后的完整代码
aov1 <- aov(Nb~Tx*Group, data=data1) tukey <- TukeyHSD(aov1) tukey.cld <- multcompLetters4(aov1, tukey) cld <- as.data.frame.list(tukey.cld$`Tx:Group`) cld summary <- data1 %>% group_by(Tx,Group) %>% summarise( w=mean(Nb), sd=sd(Nb), max=max(Nb)) %>% arrange(desc(w)) summary$Tukey <- cld$Letters # 调整文本位置匹配箱线图分组 ggplot(data1, aes(x = Group, y = Nb, fill = Tx)) + geom_boxplot(show.legend = TRUE, outlier.shape = NA, position = position_dodge(width = 0.75)) + geom_text(data = summary, aes(x = Group, label = Tukey, y = max + 1, fill = Tx), inherit.aes = FALSE, position = position_dodge(width = 0.75), size = 4)
关键调整说明
position_dodge(width = 0.75):箱线图默认分组偏移宽度为0.75,让文本使用相同参数,即可让每个Group下不同Tx的字母对应到各自箱线正上方。y = max + 1:给字母位置添加小偏移,避免与箱线图最大值重叠,可根据数据范围调整数值。- 保留
fill = Tx:确保ggplot识别分组逻辑,正确应用位置偏移。
内容的提问来源于stack exchange,提问作者arnaudm
相关产品推荐
相关产品推荐

