我正在装配包装中的gam
,并将结果存储在model
中,到目前为止,我一直在使用plot(model)
查看光滑组件。我最近开始使用ggplot2并且喜欢它的输出。所以我想知道,是否可以使用ggplot2绘制这些图?是否可以绘制与ggplot2适合的gam平滑组件?
下面是一个例子:
x1 = rnorm(1000)
x2 = rnorm(1000)
n = rpois(1000, exp(x1) + x2^2)
model = gam(n ~ s(x1, k=10) + s(x2, k=20), family="poisson")
plot(model, rug=FALSE, select=1)
plot(model, rug=FALSE, select=2)
我在s(x1, k=10)
和s(x2, k=20)
不配合我的兴趣。
部分答案:
我更深入地挖掘plot.gam
和mgcv:::plot.mgcv.smooth
,并建立了自己的功能,提取从平滑部件的预测效果和标准误差。它不处理所有的选项和plot.gam
的情况,所以我只认为它是一个部分的解决方案,但它适用于我。
EvaluateSmooths = function(model, select=NULL, x=NULL, n=100) {
if (is.null(select)) {
select = 1:length(model$smooth)
}
do.call(rbind, lapply(select, function(i) {
smooth = model$smooth[[i]]
data = model$model
if (is.null(x)) {
min = min(data[smooth$term])
max = max(data[smooth$term])
x = seq(min, max, length=n)
}
if (smooth$by == "NA") {
by.level = "NA"
} else {
by.level = smooth$by.level
}
range = data.frame(x=x, by=by.level)
names(range) = c(smooth$term, smooth$by)
mat = PredictMat(smooth, range)
par = smooth$first.para:smooth$last.para
y = mat %*% model$coefficients[par]
se = sqrt(rowSums(
(mat %*% model$Vp[par, par, drop = FALSE]) * mat
))
return(data.frame(
label=smooth$label
, x.var=smooth$term
, x.val=x
, by.var=smooth$by
, by.val=by.level
, value = y
, se = se
))
}))
}
这将返回与光滑部件的“熔融”的数据帧,因此现在可以使用ggplot
与上面的例子:如果有人知道的软件包,其允许该在
smooths = EvaluateSmooths(model)
ggplot(smooths, aes(x.val, value)) +
geom_line() +
geom_line(aes(y=value + 2*se), linetype="dashed") +
geom_line(aes(y=value - 2*se), linetype="dashed") +
facet_grid(. ~ x.var)
一般情况下我会很感激。
ggplot使用'predict'用于'geom_smooth',所以只是做'方法='gam'' –
据我所知geom_smooth它显示适合度而不是平滑度。所以我不认为这是解决方案。 – unique2
链接到一个数据集(仅仅以'mgcv'为例,作为一个起点和你试图复制的情节),我们可以(可能)告诉你如何。 –