如何在ggplot散点图中按年龄组添加多条趋势线
按年龄组添加趋势线及分组相关系数的解决方案
修正后的代码
library(ggplot2) library(ggpubr) # 可选:将Age_range转为因子,控制分组显示顺序 cars$Age_range <- factor(cars$Age_range, levels = c("20_under", "21_24", "25_29", "30_up")) ggplot(cars, aes(x = horsepower, y = miles, color = Age_range)) + geom_point(alpha = 0.6) + # 增加透明度避免点重叠 geom_smooth(method = lm, se = TRUE) + # se=TRUE显示置信区间,可设为FALSE关闭 stat_cor( method = "pearson", aes(group = Age_range), # 按年龄组单独计算相关系数 label.x = 77, label.y = c(-3000, -2500, -2000, -1500), # 为每个组设置不同y坐标避免标签重叠 position = position_dodge(width = 0.5) ) + theme_minimal()
关键问题说明
趋势线分组逻辑
原代码中geom_smooth已经能按Age_range自动生成多条趋势线,若没看到预期效果,先检查数据:- 确认每个
Age_range类别有至少2个有效数据点(线性拟合需要至少2个点) - 验证
horsepower和miles是数值型变量,而非字符型
- 确认每个
分组相关系数显示
原代码的stat_cor未指定分组,只会计算整体相关系数。添加aes(group = Age_range)后,会为每个年龄组单独计算并显示皮尔逊相关系数。标签优化
用label.y向量给每个组设置不同的垂直位置,配合position_dodge避免标签重叠,可根据你的图表实际范围调整数值。
内容的提问来源于stack exchange,提问作者ChrisSmith
相关产品推荐
相关产品推荐

