如何在分组多项式回归线外添加跨组汇总多项式回归线?
添加尊重分组逻辑的汇总回归线
要在分组多项式回归线之外添加符合分组逻辑的汇总线,有两种实用方法,具体如下:
方法1:拟合包含分组交互的整体模型
这种方法通过在模型中加入size分组与position二次多项式的交互项,拟合一条既考虑组内趋势、又整合整体规律的汇总线,直接在原有绘图代码中扩展即可:
library(tidyverse) df <- data.frame( size = c(3,3,3,4,4,4,4,5,5,5,5,5), position = c(1,2,3,1,2,3,4,1,2,3,4,5), value = c(1,2,2.5, -0.5,0.5,-0.5,1, 1.7,2,2.5,1.6,1.9) ) df %>% ggplot(aes(x = position, y = value, color = factor(size))) + geom_point() + # 分组二次多项式回归线 geom_smooth(method = "lm", formula = y ~ poly(x, 2), se = FALSE) + # 尊重分组逻辑的汇总回归线 geom_smooth( aes(color = NULL), # 取消颜色分组,使用统一样式 method = "lm", formula = y ~ factor(size) * poly(x, 2), # 加入分组与position的交互项 color = "black", linetype = "dashed", linewidth = 1, # 加粗突出汇总线 se = FALSE ) + labs(x = "Index", y = "Value", color = "Size") + theme_minimal()
方法2:先分组拟合再取平均
如果希望汇总线代表各组趋势的平均水平,可以先对每个size组单独拟合多项式,计算组内预测值后,对相同position的预测值取平均,再绘制这条平均趋势线:
# 预计算各组预测值的平均值 pred_df <- df %>% group_by(size) %>% mutate( # 分组拟合二次多项式并计算预测值 pred = predict(lm(value ~ poly(position, 2), data = cur_data())) ) %>% group_by(position) %>% summarise(avg_pred = mean(pred)) %>% # 相同position的预测值取平均 ungroup() # 绘图 df %>% ggplot(aes(x = position, y = value, color = factor(size))) + geom_point() + geom_smooth(method = "lm", formula = y ~ poly(x, 2), se = FALSE) + # 添加平均趋势的汇总线 geom_line( data = pred_df, aes(y = avg_pred, color = NULL), color = "black", linetype = "dashed", linewidth = 1 ) + labs(x = "Index", y = "Value", color = "Size") + theme_minimal()
两种方法的区别:
- 方法1的汇总线基于整体交互模型,体现包含分组效应的全局趋势;
- 方法2的汇总线是各组趋势的平均,更偏向展示组间趋势的共性。
内容的提问来源于stack exchange,提问作者Chris Ruehlemann
相关产品推荐
相关产品推荐

