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

如何在stat_compare_means()中添加样本量(n=)至检验名与P值之间?

在stat_compare_means中添加样本量(n=)

你可以通过自定义label参数实现需求,无需额外调用geom_text或annotate。stat_compare_means支持传入自定义标签函数,直接在函数内拼接检验名称、样本量与P值,让信息紧邻显示。

修改后的代码示例

library(ggplot2)
library(ggpubr)
library(dplyr)

data(iris)

# 自定义标签函数:拼接检验方法、样本量与P值
custom_label <- function(data, method, ...) {
  # 统计每组样本量并格式化
  group_ns <- table(data$Species) %>% paste0("n=", ., collapse=", ")
  # 执行统计检验获取格式化P值
  test_result <- compare_means(Sepal.Length ~ Species, data = data, method = method)
  formatted_p <- test_result$p.format
  # 拼接最终标签文本
  paste0(method, " (", group_ns, ")\nP = ", formatted_p)
}

ggplot(iris, aes(x=Species, y=Sepal.Length)) +
  geom_boxplot() +               
  geom_jitter(width = 0.1, shape=21, colour="black", fill="grey95", stroke=0.5, size=2) +
  stat_compare_means(label.y.npc = 0.93, method = "kruskal.test", 
                     label = custom_label, size = 5, family = "serif") +
  theme_classic()

说明

  • 自定义的custom_label函数会自动完成样本量统计、检验执行和文本拼接,最终输出格式为检验方法 (n=xx, n=xx, ...)\nP = 格式化P值
  • 将该函数直接传给stat_compare_means的label参数,就能让样本量信息紧邻P值显示,无需手动调整位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:42:11