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

问题描述

我正在处理 ISLR 库中的工资数据集。我的目标是在3个位置(参见下面的代码)执行与节的花键回归。我可以做这个回归。那部分很好。

我的问题涉及回归曲线的可视化。使用基本 R 函数,我似乎得到了正确的曲线。但是我似乎无法使用 tidyverse 获得完全正确的曲线。 This是期望是什么,以及我所得到的与所述基座的功能

1

This 是 ggplot 输出内容

2

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

geom_smooth()`使用方法= 'GAM' 和式“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,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,color = 'grey') +
  geom_smooth(mapping = aes(x = age.grid,y = predict(fit,newdata = list(age = age.grid))),color = 'red')

但这看起来与第二张图非常相似。

感谢您的帮助!

解决方法

来自 splines::bs()

s(.,type="bs")mgcv 做非常不同的事情;后者是一个惩罚回归样条。我会尝试(未经测试!)

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