如何用ggplot与R获取多项式回归方程?系数拟合异常排查
问题原因与解决方法
为什么手动构建的函数和ggplot趋势线不一致?
你用poly(Resolution, 3)拟合时,poly()默认生成的是正交多项式,而非我们常规理解的原始多项式(即x、x²、x³)。正交多项式的系数经过了归一化处理,目的是减少自变量间的多重共线性,因此不能直接将这些系数对应到x³、x²、x的项上,这就是两条线差异的根源。
两种解决途径
1. 使用原始多项式拟合(直接获取可复用的系数)
在poly()中添加raw=TRUE参数,强制生成原始多项式项,此时模型系数直接对应x、x²、x³的系数,可直接用来构建函数:
# 拟合原始三阶多项式模型 model_raw = lm(Bytes ~ poly(Resolution, 3, raw=TRUE), data = averaged_frame) # 输出对应原始多项式的系数 print(coef(model_raw))
输出的系数对应关系为:f(x) = (Intercept) + poly(Resolution,3,raw=TRUE)1*x + poly(Resolution,3,raw=TRUE)2*x² + poly(Resolution,3,raw=TRUE)3*x³
同时,ggplot绘图时也要同步使用raw=TRUE,确保趋势线和模型一致:
library(ggplot2) plot = ggplot(averaged_frame, aes(x = Resolution, y = Bytes)) + geom_point() + stat_smooth(method = "lm", formula = y ~ poly(x, 3, raw=TRUE), se = FALSE)
2. 基于正交多项式模型生成预测值(保留正交拟合的优势)
如果需要保留正交多项式拟合的特性(比如避免多重共线性),可以直接用模型的predict()函数生成趋势线数据,而非手动构建函数:
# 正交多项式模型(你的原代码) model_ortho = lm(Bytes ~ poly(Resolution, 3), data = averaged_frame) # 生成用于绘图的预测数据 pred_data = data.frame( Resolution = seq(min(averaged_frame$Resolution), max(averaged_frame$Resolution), length.out = 100) ) pred_data$Bytes_pred = predict(model_ortho, newdata = pred_data) # 添加到ggplot中,会和stat_smooth的趋势线完全重合 plot = ggplot(averaged_frame, aes(x = Resolution, y = Bytes)) + geom_point() + stat_smooth(method = "lm", formula = y ~ poly(x, 3), se = FALSE) + geom_line(data = pred_data, aes(y = Bytes_pred), color = "red", linetype = "dashed")
内容的提问来源于stack exchange,提问作者William Bradshaw
相关产品推荐
相关产品推荐

