You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ggplot中stat_compare_means默认检验改为Mann-Whitney检验

修改为Mann-Whitney非参数检验的代码

直接在stat_compare_means()函数中添加method = "wilcox.test"参数,即可指定使用Mann-Whitney U检验(对应R中的wilcox.test)。修改后的完整代码如下:

my_comparisons <- list (c("AA/AG","GG"))
  
df <- GDFSNP1_for_R
df  %>% 
  drop_na(Genotype) %>%
  pivot_longer(starts_with("GDF")) %>%
  mutate(name = factor(name, c("GDFb", "GDFt6", "GDFt12"))) %>%
  ggplot(. , aes(y = value, x = Genotype, group = Genotype, fill=Genotype)) + 
  facet_grid(~name, labeller = as_labeller(GDF_label)) + 
  geom_violin(width=0.9) +
  geom_boxplot(width=0.1, alpha=0.2) + 
  stat_compare_means(comparisons = my_comparisons, method = "wilcox.test")
stat_compare_means支持的检验方法列表

stat_compare_means(来自ggsignif包)支持的检验方法可按分组数量分类:

两组比较场景

  • t.test:默认参数t检验(要求数据服从正态分布、方差齐性)
  • wilcox.test:Mann-Whitney U检验(非参数方法,适配非正态分布数据)
  • t.test.welch:Welch校正t检验(用于方差不齐的正态分布数据)

多组比较场景

  • anova:单因素方差分析(参数检验,要求正态分布、方差齐性)
  • kruskal.test:Kruskal-Wallis H检验(非参数方法,适配多组非正态分布数据)
  • oneway.test:Welch校正单因素方差分析(用于方差不齐的多组正态分布数据)

额外说明:可通过method.args参数传递检验的附加参数,比如指定paired = TRUE执行配对检验,或var.equal = FALSE明确方差不齐等。

内容的提问来源于stack exchange,提问作者statsnoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 14:35:02