簡體   English   中英

如何使用 ggplot2 可視化樣條回歸?

[英]How to visualize spline regression with 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')

但這看起來與第二張圖片非常相似。

謝謝你的幫助!

來自mgcvsplines::bs()s(., type="bs")做的事情非常不同; 后者是懲罰回歸樣條。 我會嘗試(未經測試!)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM