类似ggpubr效果的ggplot添加置信区间文本的优雅实现方法
解决方案
有两种成熟的实现方式,都支持自动适配分组、分面场景,无需手动预计算每个分组的统计值:
方案1:使用ggpmisc包(便捷开箱)
ggpmisc是ggplot2生态中专门用于统计注释的拓展包,其stat_correlation()函数原生支持输出相关系数、p值与置信区间,用法和ggpubr::stat_cor几乎一致:
单图示例代码
library(ggplot2) library(ggpmisc) # 测试数据和你提供的一致 set.seed(123) n <- 1000 x_vec <- runif(n) y_vec <- 3 + 1.3*x_vec + rnorm(n) df <- data.frame(x = x_vec, y = y_vec) ggplot(df, aes(x, y)) + geom_point() + stat_correlation( use_label = c("r", "p", "ci"), # 指定显示的内容:相关系数、p值、置信区间 p.digits = 5, # p值保留位数,和你原参数p.accuracy效果一致 ci.digits = 3, # 置信区间保留位数 x = "left", y = "top", # 位置和原stat_cor保持一致 hjust = 0, vjust = 1 )
分面示例代码
# 生成分组数据 df <- data.frame(x = x_vec, y = y_vec, grp = sample(1:4, n, replace=TRUE)) ggplot(df, aes(x, y, group = grp)) + geom_point() + facet_wrap(vars(grp)) + stat_correlation( use_label = c("r", "p", "ci"), p.digits = 5, x = "left", y = "top", hjust = 0, vjust = 1 )
可通过conf.level参数自定义置信区间的置信水平,默认值为0.95。
方案2:自定义Stat层(纯原生无额外依赖)
如果不想额外安装第三方包,可以直接自定义ggplot2的统计层,完全自主控制输出格式:
# 自定义统计层逻辑 StatCorCI <- ggproto("StatCorCI", Stat, compute_group = function(data, scales, conf.level = 0.95, p.digits = 5) { # 每组自动计算cor.test结果 cor_res <- cor.test(data$x, data$y, conf.level = conf.level) # 返回注释文本和位置 data.frame( x = min(data$x, na.rm = TRUE), y = max(data$y, na.rm = TRUE), label = paste0( "r = ", round(cor_res$estimate, 3), "\n", "p = ", signif(cor_res$p.value, p.digits), "\n", "95% CI: [", round(cor_res$conf.int[1], 3), ", ", round(cor_res$conf.int[2], 3), "]" ) ) }, required_aes = c("x", "y") ) # 封装成调用函数 stat_cor_ci <- function(mapping = NULL, data = NULL, geom = "text", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( stat = StatCorCI, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } # 分面场景调用示例 ggplot(df, aes(x, y, group = grp)) + geom_point() + facet_wrap(vars(grp)) + stat_cor_ci(hjust = 0, vjust = 1)
该方案灵活性最高,可根据需求自由调整注释文本的内容、格式、位置。
内容的提问来源于stack exchange,提问作者Gumeo
相关产品推荐
相关产品推荐

