R GAM 可视化,geom_smooth 不适合所有观察到的数据

R GAM visualisation, geom_smooth not fit to all observed data

我使用以下代码在 R 中制作了一个 GAM 模型:

mod_gam1 <-gam(y ~ s(ï..x), data=Bird.data, method = "REML") 情节(mod_gam1) 系数(mod_gam1) 情节(mod_gam1,残差=真,pch=1) 系数(mod_gam1)

mod_gam1$fitted.values

result <- data.frame(data = c(mod_gam1$fitted.values, Bird.data$y), Year = rep(1991:2019, times = 2 ), 'source' = c(rep('Modelled', 次 = 29), rep('Observed', 次 = 29))) ggplot(result, aes(x = Year, y = data, color = source))+ geom_point()+ geom_smooth(span= 0.8)+labs(x="Year", y = "鸟岛碎片总数")+ scale_y_continuous(limits = c(0,1000))

并且输出看起来不错,但是 geom_smooth 错误的阴影区域没有扩展到我的整个数据集(在我的前两个数据点之前停止),我不确定为什么?

如有任何帮助,我们将不胜感激!

我无法上传图片,因为我是该网站的新手,但是基本上我有两个数据集(观察值和 GAM 建模值),它们都有自己的 SE 置信度带,但是这些开始了我的两个数据点数据集不在第一点。

这些是我的数据点: Bird.data

ï..x y
1991 17
1992 76
1993 328
1994 131
1995 425
1996 892
1997 501
1998 419
1999 297
2000 277
2001 310
2002 282
2003 189
2004 278
2005 322
2006 444
2007 412
2008 241
2009 242
2010 255
2011 289
2012 335
2013 279
2014 628
2015 500
2016 174
2017 636
2018 420
2019 447

拟合值

[1] 95.56189 177.01468 255.17074 324.97532 380.28813 415.71334 428.67793 420.86624 398.18522 369.06325 [11] 341.72715 321.65585 310.33971 305.81158 304.53360 303.60521 302.21413 301.75501 304.77184 313.43400 [21] 328.37279 348.39076 371.04203 393.66222 414.29754 432.15104 447.48020 461.14595 474.09266

负二项式 link to graph image

这是因为您使用 scale_y_continuous 设置的限制。如果您删除该线(或向下调整 y,使其允许平滑的最小 y 值,那么您将完全看到平滑填充。

但是,你这里有一个更大的问题。您实际上并没有在平滑中显示 gam 模型(仅显示 gam 点预测)。有几种方法可以做到这一点。最简单的方法可能是将 Bird.data 直接提供给 ggplot 函数,并使用 geom_smooth()methodformula 参数来直接请求gam smooth:

ggplot(Bird.data, aes(x,y)) + 
  geom_point() + 
  geom_smooth(method="gam", formula=y~s(x)) +
  labs(x="Year", y = "Bird Island Total Debris Count")

这种方法的问题是您也无法获得预测点。这可以通过以下方法解决

  1. 将 se 直接添加到 result 数据框
result$se = c(predict(mod_gam1,se=T)$se, rep(NA,29))
  1. 像以前一样使用 ggplot,但使用 geom_ribbon,直接设置 yminymax
ggplot(result, aes(x = Year, y = data, colour = source, fill=source))+
  geom_point()+ 
  geom_ribbon(aes(ymin=data-1.96*se, ymax=data+1.96*se), alpha=0.2) +
  labs(x="Year", y = "Bird Island Total Debris Count")+
  scale_y_continuous(limits = c(-200,1000))