来自mgcv :: gamm的ggplot2 geom_ribbon

时间:2018-02-21 13:43:08

标签: r ggplot2 prediction

我正在尝试根据gamm模型的预测添加一个功能区,这似乎比预期更难,因为gamm与gam有些不同。

我首先尝试直接使用geom_stat,但这不起作用(并且不会使用我的整个模型,其中还包括其他几个协变量)

library(tidyverse); library(mgcv)

dt = cbind(V1=scale(sample(1000)), 
    Age=rnorm(n = 1000, mean = 40, sd = 10), 
    ID=rep(seq(1:500),each=2) %>% as.data.frame()

# Works fine ----
dt %>% ggplot(aes(x=Age, y=V1)) + 
   stat_smooth(method="gam", formula= y~s(x,bs="cr")) 

# Fails horribly :P 
dt %>% ggplot(aes(x=Age, y=V1)) + 
    stat_smooth(method="gamm", formula= y~s(x,bs="cr"))

Maximum number of PQL iterations:  20   
iteration 1  
Warning message:  
Computation failed in `stat_smooth()`:  
no applicable method for 'predict' applied to an object of class "c('gamm', 'list')"   

我尝试在模型$ gamm上使用预测功能,但我不知道如何使用它,以及如何制作CI功能区

dt.model = gamm(V1 ~ s(Age, bs="cr") + s(ID, bs = 're'), data=dt, family="gaussian", discrete=T)

dt$pred = predict(dt.model$gam)

dt %>% ggplot(aes(x = Age, y = V1)) +
   geom_line(aes(group=ID), alpha=.3) +
   geom_point(alpha=.2) +
   geom_smooth(aes(y=pred))

我认识到这是一个糟糕的示例数据,因为这是一个愚蠢的形状。 但我希望能够像model.fit预测的那样在线上添加带有CI的功能区。而且我更喜欢在ggplot中这样做,特别是因为我想在后台使用spagetti图。

1 个答案:

答案 0 :(得分:2)

se.fit=TRUE内使用predict

library(tidyverse)
library(mgcv)

dt <- cbind(V1=scale(sample(1000)), 
    Age=rnorm(n = 1000, mean = 40, sd = 10), 
    ID=rep(seq(1:500),each=2)) %>% as.data.frame()

dt.model <- gamm(V1 ~ s(Age, bs="cr") + s(ID, bs = "re"), 
           data=dt, family="gaussian", discrete=T)

pred <- predict(dt.model$gam, se.fit=T)

dt %>% ggplot(aes(x = Age, y = V1)) +
   geom_line(aes(group=ID), alpha=.3) +
   geom_point(alpha=.2) +
   geom_ribbon(aes(ymin=pred$fit-1.96*pred$se.fit,
                   ymax=pred$fit+1.96*pred$se.fit), alpha=0.2, fill="red")+
   geom_line(aes(y=pred$fit), col="blue", lwd=1)

enter image description here

相关问题