如何使用 ggplot2 可视化样条回归?

How to visualize spline regression with ggplot2?

我正在使用 ISLR 库中的 Wage 数据集。我的 objective 是在 3 个位置执行带结的样条回归(见下面的代码)。我可以做这个回归。那部分没问题。

我的问题涉及回归曲线的可视化。使用基本 R 函数,我似乎得到了正确的曲线。但我似乎无法使用 tidyverse 获得完全正确的曲线。 This 是预期的,也是我通过基本函数得到的:

This 是 ggplot 吐出来的

明显不同。当 运行 ggplot 函数时,R 给我以下消息:

geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")

这是什么意思,我该如何解决?

library(tidyverse)
library(ISLR)
attach(Wage)

agelims <- range(age)
age.grid <- seq(from = agelims[1], to = agelims[2])

fit <- lm(wage ~ bs(age, knots = c(25, 40, 60), degree = 3), data = Wage) #Default is 3

plot(age, wage, col = 'grey', xlab = 'Age', ylab = 'Wages')
points(age.grid, predict(fit, newdata = list(age = age.grid)), col = 'darkgreen', lwd = 2, type = "l")
abline(v = c(25, 40, 60), lty = 2, col = 'darkgreen')

ggplot(data = Wage) +
  geom_point(mapping = aes(x = age, y = wage), color = 'grey') +
  geom_smooth(mapping = aes(x = age, y = fit$fitted.values), color = 'red')

我也试过了

ggplot() +
  geom_point(data = Wage, mapping = aes(x = age, y = wage), color = 'grey') +
  geom_smooth(mapping = aes(x = age.grid, y = predict(fit, newdata = list(age = age.grid))), color = 'red')

不过和第二张图很像。

感谢您的帮助!

splines::bs()mgcv 中的 s(., type="bs") 做的事情截然不同;后者是 penalized 回归样条。我会尝试(未经测试!)

geom_smooth(method="lm",
   formula=  y ~ splines::bs(x, knots = c(25, 40, 60), degree = 3))