I have run a smoothing procedure on my data using splines, and have managed to plot the smoothed spline line on top of my data points. However, I also need to plot the confidence intervals of the spline function in the same plot, which I can't seem to be able to do.
My data frame:
dput(df)
structure(list(x = c(1970, 1971, 1972, 1973, 1974, 1975, 1976,
1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987,
1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
2010, 2011, 2012, 2013, 2014, 2015, 2016), y = c(1271, 739, 744,
591, 682, 666, 755, 718, 668, 732, 795, 922, 908, 937, 1009,
824, 783, 840, 859, 877, 891, 810, 840, 784, 702, 712, 666, 747,
711, 790, 744, 664, 755, 803, 760, 780, 741, 734, 629, 623, 587,
760, 863, 816, 722, 713, 698)), class = "data.frame", row.names = c(NA,
-47L))
I fit the spline using the package mgcv
:
library(mgcv)
m.all <- gam(y~s(x),family=poisson,data=df)
plot(df$y ~ df$x)
lines(fitted(m.all) ~ df$x)
If I plot the model plot(m.all)
I get the spline line and the confidence intervals, but with a y-axis corresponding to some internal spline calculations, not suitable for plotting the data points at the same time.
How do I tweak my script to be able to include the confidence intervals of the smoothed spline in my plot?