如何为含交互项的回归绘制分组附加变量图/偏回归图?
含交互项回归模型的分组附加变量图实现
问题背景
我需要为包含交互项的线性回归模型绘制附加变量图(Added Variable Plot),并为Species分组单独绘制偏回归系数回归线。目前用car包的avPlots()能生成基础图,但无法实现分组回归线,现寻求实现方法。
基础实现代码(car包):
# 加载包并拟合含交互项的模型 library(car) lm1 <- lm(data = iris, Petal.Length ~ Sepal.Width + Sepal.Length*Species) # 生成基础附加变量图 avPlots(lm1) # 单独绘制交互项的附加变量图 avPlots(lm1, terms = "Sepal.Length:Species")
你之前提供的ggplot示意代码使用了原始变量而非附加变量图要求的残差,因此需要调整为基于残差的绘图逻辑。
手动实现分组附加变量图
附加变量图的核心是展示残差对残差的关系:
- X轴:目标自变量对模型中其余所有变量回归后的残差(剔除其他变量的影响)
- Y轴:响应变量对模型中其余所有变量回归后的残差(剔除其他变量的影响)
我们可以手动计算这两组残差,再用ggplot2按Species分组绘制回归线:
完整代码
library(ggplot2) # 1. 计算X残差:Sepal.Width 对模型中除自身外的所有变量回归的残差 x_resid <- residuals(lm(data = iris, Sepal.Width ~ Sepal.Length + Species + Sepal.Length:Species)) # 2. 计算Y残差:Petal.Length 对模型中除Sepal.Width外的所有变量回归的残差 y_resid <- residuals(lm(data = iris, Petal.Length ~ Sepal.Length + Species + Sepal.Length:Species)) # 3. 合并残差到原数据集 iris_resid <- cbind(iris, x_resid, y_resid) # 4. 绘制分组附加变量图 ggplot(iris_resid, aes(x = x_resid, y = y_resid, color = Species)) + geom_point(alpha = 0.7) + # 绘制散点,alpha调整透明度避免重叠 geom_smooth(method = "lm", se = FALSE) + # 绘制分组回归线(关闭置信区间) labs( x = "残差:Sepal.Width ~ Sepal.Length + Species + Sepal.Length:Species", y = "残差:Petal.Length ~ Sepal.Length + Species + Sepal.Length:Species", color = "物种", title = "按Species分组的Sepal.Width附加变量图" ) + theme_minimal()
扩展:绘制交互项的分组附加变量图
如果需要为交互项Sepal.Length:Species绘制分组回归线,只需调整残差计算的目标变量:
# 计算交互项的残差(X轴) int_resid <- residuals(lm(data = iris, Sepal.Length:Species ~ Sepal.Width + Sepal.Length + Species)) # 计算响应变量对除交互项外的所有变量的残差(Y轴) y_resid_int <- residuals(lm(data = iris, Petal.Length ~ Sepal.Width + Sepal.Length + Species)) # 合并数据并绘图 iris_int_resid <- cbind(iris, int_resid, y_resid_int) ggplot(iris_int_resid, aes(x = int_resid, y = y_resid_int, color = Species)) + geom_point(alpha = 0.7) + geom_smooth(method = "lm", se = FALSE) + labs( x = "残差:Sepal.Length:Species ~ Sepal.Width + Sepal.Length + Species", y = "残差:Petal.Length ~ Sepal.Width + Sepal.Length + Species", color = "物种", title = "按Species分组的Sepal.Length:Species附加变量图" ) + theme_minimal()
内容的提问来源于stack exchange,提问作者user14278898
相关产品推荐
相关产品推荐

