几年前的这个主题描述了如何提取用于绘制拟合gam模型的平滑组件的数据.它有效,但只有当有一个平滑变量时才有效.我有多个平滑变量,不幸的是我只能从系列的最后一个中提取平滑.这是一个例子:
library(mgcv)
a = rnorm(100)
b = runif(100)
y = a*b/(a+b)
mod = gam(y~s(a)+s(b))
summary(mod)
plotData <- list()
trace(mgcv:::plot.gam, at=list(c(25,3,3,3)),
#this gets you to the location where plot.gam calls plot.mgcv.smooth (see ?trace)
#plot.mgcv.smooth is the function that does the actual plotting and
#we simply assign its main argument into the global workspace
#so we can work with it later.....
quote({
#browser()
plotData <<- c(plotData, pd[[i]])
}))
plot(mod,pages=1)
plotData
Run Code Online (Sandbox Code Playgroud)
我试图让两个估计的平滑函数a
和b
,但列表plotData
只给我估计b
.我已经研究了plot.gam …
我需要在ggplot中创建一些gam图.我可以用普通的绘图功能来完成它们,但我不确定如何处理ggplot.这是我的代码和情节与常规绘图功能.我正在使用ISLR包中的College数据集.
train.2 <- sample(dim(College)[1],2*dim(College)[1]/3)
train.college <- College[train.2,]
test.college <- College[-train.2,]
gam.college <- gam(Outstate~Private+s(Room.Board)+s(Personal)+s(PhD)+s(perc.alumni)+s(Expend)+s(Grad.Rate), data=train.college)
par(mfrow=c(2,2))
plot(gam.college, se=TRUE,col="blue")
Run Code Online (Sandbox Code Playgroud)