首页 > 解决方案 > 如何使用 ggplot2 可视化样条回归?

问题描述

我正在使用 ISLR 库中的工资数据集。我的目标是在 3 个位置执行带结的样条回归(参见下面的代码)。我可以做这个回归。那部分很好。

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

1

就是 ggplot 吐出来的

2

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

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, 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')

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

谢谢你的帮助!

标签: rggplot2spline

解决方案


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

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

推荐阅读