R 使用 ggplot 绘制置信带 [英] R Plotting confidence bands with ggplot

查看:36
本文介绍了R 使用 ggplot 绘制置信带的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为装有 gls 的模型创建一个置信带,如下所示:

I would like to create a confidence band for a model fitted with gls like this:

require(ggplot2)
require(nlme)

mp <-data.frame(year=c(1990:2010))

mp$wav <- rnorm(nrow(mp))*cos(2*pi*mp$year)+2*sin(rnorm(nrow(mp)*pi*mp$wav))+5
mp$wow <- rnorm(nrow(mp))*mp$wav+rnorm(nrow(mp))*mp$wav^3

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

mp$fit <- as.numeric(fitted(m01))

p <- ggplot(mp, aes(year, wow))+ geom_point()+ geom_line(aes(year,fit))
p

这只绘制了拟合值和数据,我想要

This only plots the fitted values and the data, and I would like something in the style of

p <- ggplot(mp, aes(year, wow))+ geom_point()+ geom_smooth()
p

但是使用 gls 模型生成的波段.

but with the bands generated by the gls model.

谢谢!

推荐答案

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

获取拟合值(同m01$fitted)

fit <- predict(m01)

通常我们可以使用类似 predict(...,se.fit=TRUE) 来获得预测的置信区间,但 gls 不提供这种能力.我们使用的配方类似于 http://glmm.wikidot.com/faq 中所示的配方:

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

组合一个预测框架":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

现在用 geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

如果我们针对 wav 而不是 year 绘图,更容易看出我们得到了正确的答案:

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

以更高的分辨率进行预测会很好,但是用 poly() 拟合的结果来做这个有点棘手——请参阅 ?makepredictcall.

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

这篇关于R 使用 ggplot 绘制置信带的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆