【发布时间】:2021-04-02 00:24:58
【问题描述】:
我正在使用 ISLR 库中的 Wage 数据集。我的目标是在 3 个位置执行带结的样条回归(请参见下面的代码)。我可以做这个回归。那部分很好。
我的问题涉及回归曲线的可视化。使用基本 R 函数,我似乎得到了正确的曲线。但我似乎无法使用 tidyverse 获得完全正确的曲线。 This 是预期的,也是我使用基本功能得到的:
This 是 ggplot 吐出来的
明显不同。 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')
但这看起来与第二张图片非常相似。
感谢您的帮助!
【问题讨论】:
-
PS
attach()几乎从不推荐...