线性模型诊断:在 ggplot2 中获得的平滑线与使用基图获得的平滑线不同

Linear model diagnostics: smoothing line obtained in ggplot2 is different from the one obtained with base plot

我正在尝试使用 ggplot2 重现线性回归模型的诊断图。我得到的平滑线与使用基图或 ggplot2::autoplot.

获得的平滑线不同
library(survival)
library(ggplot2)
model <- lm(wt.loss ~ meal.cal, data=lung)
## Fitted vs. residuals using base plot:
plot(model, which=1)
## Fitted vs. residuals using ggplot
model.frame <- fortify(model)
ggplot(model.frame, aes(.fitted, .resid)) + geom_point() + geom_smooth(method="loess", se=FALSE)

平滑线不同,前面几个点的影响用ggplot提供的loess方法要大很多。我的问题是:如何使用 ggplot2 重现通过 plot() 获得的平滑线?

您可以使用同名基函数计算 lowess,它用于在原始诊断图中绘制红线。

smoothed <- as.data.frame(with(model.frame, lowess(x = .fitted, y = .resid)))

ggplot(model.frame, aes(.fitted, .resid)) + 
  theme_bw() +
  geom_point(shape = 1, size = 2) + 
  geom_hline(yintercept = 0, linetype = "dotted", col = "grey") +
  geom_path(data = smoothed, aes(x = x, y = y), col = "red")

和原来的: