[英]Plotting smooth functions from a gam (using type = 'terms')
這更像是對最近提出的類似問題的跟進,所以希望這是一個更好/不那么模糊的問題。
我創建了一個 GAM 並繪制了兩個平滑函數(在同一個圖上或兩個單獨的圖上),我失敗的是如何繪制我在預測中得到的 2 列。 由於稍后的季節性趨勢,我需要在我的模型中保留一個月以創建預測。
mod = gam(co2 ~ s(timeStep, k = 200, bs = "cs") + s(month, k = 12, bs = "cc"),
data = carbonD,
family = gaussian(link = "identity"))
#predictions
preds = predict(carbonD_model3, newdata, type = 'terms', se.fit = TRUE)
preds$fit
s(timeStep) s(month)
1 -21.023636218 -0.44138402
2 -20.710943557 -0.36466359
3 -20.512344518 0.04800245
4 -20.532656726 1.15111508
5 -20.763446687 1.92491535
6 -21.120504411 1.80493059
#attempt at plotting but gives aesthetics errors
ggplot(newdata, aes(timeStep, co2)) +
geom_line(aes(timeStep, preds), col = 'red')
也知道這可以像這樣(如下)以某種方式完成,但想讓我的預測使用這種方法是可能的。
plot(mod)
這對我有用:
data(mtcars)
library(mgcv)
#> Loading required package: nlme
#> This is mgcv 1.8-40. For overview type 'help("mgcv-package")'.
library(ggplot2)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following object is masked from 'package:nlme':
#>
#> collapse
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
m1 <- gam(mpg ~ s(hp) + s(wt), data=mtcars)
preds <- predict(m1, type="terms")
mf <- model.frame(m1)
mf <- bind_cols(mf, preds)
ggplot(mf, aes(x=hp, y=`s(hp)`)) +
geom_line()
ggplot(mf, aes(x=wt, y=`s(wt)`)) +
geom_line()
由reprex 包(v2.0.1)於 2022-06-27 創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.