R - 基本图形中指数模型 (nls) 的置信带

R - Confidence bands for exponential model (nls) in basic graphics

我正在尝试绘制指数曲线(nls 对象)及其置信带。 在 Ben Bolker 的回复之后,我可以很容易地在 ggplot 中完成 post. 但我想以基本图形样式绘制它,(也使用异形多边形)

df <- 
structure(list(x = c(0.53, 0.2, 0.25, 0.36, 0.46, 0.5, 0.14, 
0.42, 0.53, 0.59, 0.58, 0.54, 0.2, 0.25, 0.37, 0.47, 0.5, 0.14, 
0.42, 0.53, 0.59, 0.58, 0.5, 0.16, 0.21, 0.33, 0.43, 0.46, 0.1, 
0.38, 0.49, 0.55, 0.54), 
y = c(63, 10, 15, 26, 34, 32, 16, 31,26, 37, 50, 37, 7, 22, 13, 
21, 43, 22, 41, 43, 26, 53, 45, 7, 12, 25, 23, 31, 19, 
37, 24, 50, 40)), 
.Names = c("x", "y"), row.names = c(NA, -33L), class = "data.frame")

m0 <- nls(y~a*exp(b*x), df, start=list(a= 5, b=0.04))
summary(m0)

coef(m0)
#   a        b 
#9.399141 2.675083 

df$pred <- predict(m0)
library("ggplot2"); theme_set(theme_bw())
g0 <- ggplot(df,aes(x,y))+geom_point()+
        geom_smooth(method="glm",family=gaussian(link="log"))+
        scale_colour_discrete(guide="none")

提前致谢!

与 R 相比,这似乎更像是一个关于统计的问题。了解 "confidence interval" 的来源非常重要。有很多方法可以构建一个。

为了在 R 中绘制阴影区域图,我假设我们可以 add/subtract 2 "standard errors" 来自 nls 拟合值来生成该图.应该检查此程序。

df <- 
  structure(list(x = c(0.53, 0.2, 0.25, 0.36, 0.46, 0.5, 0.14, 
                       0.42, 0.53, 0.59, 0.58, 0.54, 0.2, 0.25, 0.37, 0.47, 0.5, 0.14, 
                       0.42, 0.53, 0.59, 0.58, 0.5, 0.16, 0.21, 0.33, 0.43, 0.46, 0.1, 
                       0.38, 0.49, 0.55, 0.54), 
                 y = c(63, 10, 15, 26, 34, 32, 16, 31,26, 37, 50, 37, 7, 22, 13, 
                       21, 43, 22, 41, 43, 26, 53, 45, 7, 12, 25, 23, 31, 19, 
                       37, 24, 50, 40)), 
            .Names = c("x", "y"), row.names = c(NA, -33L), class = "data.frame")

m0 <- nls(y~a*exp(b*x), df, start=list(a= 5, b=0.04))
df$pred <- predict(m0)
se = summary(m0)$sigma
ci = outer(df$pred, c(outer(se, c(-1,1), '*'))*1.96, '+')
ii = order(df$x)
# typical plot with confidence interval
with(df[ii,], plot(x, pred, ylim=range(ci), type='l'))
matlines(df[ii,'x'], ci[ii,], lty=2, col=1)
# shaded area plot
low = ci[ii,1]; high = ci[ii,2]; base = df[ii,'x']
polygon(c(base,rev(base)), c(low,rev(high)), col='grey')
with(df[ii,], lines(x, pred, col='blue'))
with(df, points(x, y))

不过我觉得下面的剧情更好看:

经过多次修改后,我尝试使用此代码,最后以不同的形式重写了所有代码。在我的例子中,问题是在原始点上扩展线。绘制线和多边形的主要概念点是距预测点 add/subtract 1.96*SE。即使并非所有数据都覆盖了所有范围,此修改也允许拟合完美的曲线。

xnew <- seq(min(df$x),max(df$x),0.01) #range
RegLine <- predict(m0,newdata = data.frame(x=xnew))
plot(df$x,df$y,pch=20)
lines(xnew,RegLine,lwd=2)
lines(xnew,RegLine+summary(m0)$sigma,lwd=2,lty=3)
lines(xnew,RegLine-summary(m0)$sigma,lwd=2,lty=3)

#example with lines up to graph border
plot(df$x,df$y,xlim=c(0,0.7),pch=20)
xnew <- seq(par()$usr[1],par()$usr[2],0.01)
RegLine <- predict(m0,newdata = data.frame(x=xnew))
lines(xnew,RegLine,lwd=2)
lines(xnew,RegLine+summary(m0)$sigma*1.96,lwd=2,lty=3)
lines(xnew,RegLine-summary(m0)$sigma*196,lwd=2,lty=3)