简体   繁体   English

从游戏中绘制平滑函数(使用 type = 'terms')

[英]Plotting smooth functions from a gam (using type = 'terms')

This is more of a follow up from a similar question asked recently, so hopefully this is a better/less vague question.这更像是对最近提出的类似问题的跟进,所以希望这是一个更好/不那么模糊的问题。

I have created a GAM and with to plot both smooth functions (on the same plot or two separate), what i'm failing with is how to plot the 2 columns i get in my predictions.我创建了一个 GAM 并绘制了两个平滑函数(在同一个图上或两个单独的图上),我失败的是如何绘制我在预测中得到的 2 列。 I need to keep month in my model for creating predictions due to the seasonal trend later down the line.由于稍后的季节性趋势,我需要在我的模型中保留一个月以创建预测。

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

Also aware that this can be done someway like this (below), but would like to get my predictions working using this method is possible.也知道这可以像这样(如下)以某种方式完成,但想让我的预测使用这种方法是可能的。

plot(mod)

在此处输入图像描述

This works for me:这对我有用:

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()

Created on 2022-06-27 by the reprex package (v2.0.1)reprex 包(v2.0.1)于 2022-06-27 创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM