如何在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
相关产品推荐
相关产品推荐

