如何在stat_poly_eq的geom_smooth相关图中添加95%置信区间标签
问题:在ggplot2的stat_poly_eq中添加相关系数95%置信区间标签
我在绘制数据相关图时,需要在标签中同时报告R²值和相关系数的95%置信区间(CI),尝试在stat_poly_eq的label参数中添加after_stat(conf.int.label),但出现错误提示找不到该对象。
我的代码如下:
Kan.PS_moc_plot <- Fnlcor_df %>% ggplot(aes(x= PSKannada, y= MOC))+ geom_smooth(method = "lm", se = TRUE, alpha = 0.5)+ geom_point(size = 2)+ stat_poly_eq(method = "lm", aes(label= paste(after_stat(rr.label), after_stat(p.value.label), after_stat(conf.int.label), sep = "*\",\"*")), label.x = "right", label.y = "bottom", size=4, family = "Palatino") + labs(y=" MOC Median RT diffecrence (sec)", x="Kannada Phoneme Segmenation")+ facet_wrap(.~paste("Age Range:", AgeRange) + paste("Group:", Group)) + theme_classic() Kan.PS_moc_plot
运行后出现以下错误:
`geom_smooth()` using formula = 'y ~ x' Error in `stat_poly_eq()`: ! Problem while mapping stat to aesthetics. ℹ Error occurred in the 3rd layer. Caused by error in `after_stat()`: ! object 'conf.int.label' not found Run `rlang::last_trace()` to see where the error occurred.
解决方案
stat_poly_eq本身并未内置conf.int.label这个统计量,要实现需求,需要手动分组计算所需统计量,再添加到图中,步骤如下:
分组计算R²和置信区间
借助broom包拟合线性模型,按AgeRange和Group分组提取R²值以及相关系数的95%置信区间:library(broom) library(dplyr) # 分组计算统计指标 stats_df <- Fnlcor_df %>% group_by(AgeRange, Group) %>% do({ model <- lm(MOC ~ PSKannada, data = .) tidy_model <- tidy(model, conf.int = TRUE) %>% filter(term == "PSKannada") r_sq <- summary(model)$r.squared tibble( r_squared = r_sq, conf_low = tidy_model$conf.low, conf_high = tidy_model$conf.high ) }) %>% ungroup() %>% mutate( r_sq_label = sprintf("R² = %.3f", r_squared), ci_label = sprintf("95%% CI: [%.3f, %.3f]", conf_low, conf_high) )修改绘图代码,添加自定义标签
使用geom_text()将计算好的标签添加到图中,定位在右下角(和原代码的label.x = "right", label.y = "bottom"一致):Kan.PS_moc_plot <- Fnlcor_df %>% ggplot(aes(x = PSKannada, y = MOC)) + geom_smooth(method = "lm", se = TRUE, alpha = 0.5) + geom_point(size = 2) + # 添加自定义统计标签 geom_text( data = stats_df, aes(x = Inf, y = -Inf, label = paste(r_sq_label, ci_label, sep = "\n")), hjust = 1, vjust = 0, size = 4, family = "Palatino" ) + labs( y = "MOC Median RT difference (sec)", x = "Kannada Phoneme Segmentation" ) + facet_wrap(.~paste("Age Range:", AgeRange) + paste("Group:", Group)) + theme_classic() Kan.PS_moc_plot
内容的提问来源于stack exchange,提问作者Arpitha
相关产品推荐
相关产品推荐

