ggplot分面绘图时wilcox.test结果重叠原因及显著性条添加方法
问题解决方法
1. 修正基础代码问题
你原有代码中stat_compare_means行末尾遗漏了+,会导致运行报错,先修正该问题。
2. 解决wilcoxon检验结果重叠问题
可以通过调整stat_compare_means的位置参数实现,常用调整参数如下:
vjust:垂直方向偏移量,正值向上偏移,负值向下偏移hjust:水平方向偏移量label.y:手动指定检验标签的y轴位置,传入数值向量即可给不同比较指定不同高度,避免重叠
示例代码:
library(ggplot2) library(ggpubr) ggplot(df, aes(y = count, x = time, group = time)) + theme_bw() + geom_boxplot()+ theme(legend.position = "none")+ scale_y_log10(limits = c(1, 300)) + # 稍微调大y轴上限,给标签预留空间 facet_wrap(vars(cluster), scales = "fixed")+ stat_compare_means(method= "wilcox.test", vjust = -0.5, label.y = c(200, 230, 260)) + # 三个两两比较的标签分别放在不同高度 labs(y = "Clone count", x = "Time point")
3. 添加显著性条
可以用ggsignif包的geom_signif函数实现,指定需要比较的分组对、显著性条放置高度即可,示例代码:
library(ggplot2) library(ggpubr) library(ggsignif) ggplot(df, aes(y = count, x = time, group = time)) + theme_bw() + geom_boxplot()+ theme(legend.position = "none")+ scale_y_log10(limits = c(1, 350)) + # 进一步放大y轴上限,给显著性条预留空间 facet_wrap(vars(cluster), scales = "fixed")+ # 添加显著性条 geom_signif(comparisons = list(c("Day 0", "Day 1"), c("Day 1", "Day 2"), c("Day 0", "Day 2")), y_position = c(150, 220, 290), # 每个显著性条的放置高度 tip_length = 0.01, # 显著性条两端竖线的长度 map_signif_level = TRUE) + # 自动将p值转换为星号标注,不需要可删除该参数 labs(y = "Clone count", x = "Time point")
如果你想要显示具体p值而非星号,把
map_signif_level = TRUE替换为test = "wilcox.test"即可。
内容的提问来源于stack exchange,提问作者Chinemerem
相关产品推荐
相关产品推荐

