r - 如何使用 ggplot2 可视化样条回归?
问题描述
我正在使用 ISLR 库中的工资数据集。我的目标是在 3 个位置执行带结的样条回归(参见下面的代码)。我可以做这个回归。那部分很好。
我的问题涉及回归曲线的可视化。使用基本 R 函数,我似乎得到了正确的曲线。但我似乎无法使用 tidyverse 获得完全正确的曲线。 这是预期的,也是我使用基本功能得到的:
这就是 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')
但这看起来与第二张图片非常相似。
谢谢你的帮助!
解决方案
splines::bs()
s(., type="bs")
从做非常不同的mgcv
事情;后者是惩罚回归样条。我会尝试(未经测试!)
geom_smooth(method="lm",
formula= y ~ splines::bs(x, knots = c(25, 40, 60), degree = 3))
推荐阅读
- c# - 如何将条件订单与 EntityFramework/linq 一起使用
- reactjs - 反应:更新状态,映射状态以显示列表但列表在一秒钟后从视图中消失?
- batch-file - cmd删除文件文件夹WIN 10内容的想法?
- python - 如何使用不和谐 python 库在不和谐的文本通道中删除整个消息
- html - 我使用 CSS 网格错了吗?
- javascript - Electron js win.webContents.print 回调函数不起作用?
- python - Flask-socketio 在路由中发出
- c# - Office365 单点注销
- jmeter - 如何在 Jmeter 中获取采样器的直接父名称
- scala - Scala 类设置器中的空间问题