R:用x中每个预测值的置信区间绘制拟合模型

时间:2014-12-13 21:53:20

标签: r plot nls

我如何绘制拟合模型,每个预测值的置信区间(x = 5,10,15,20,25,30,35)?

对于下一个数据集

df<-data.frame(
  x = rep(c( 5, 10, 15,  20,  25, 30, 35), each=4 ), 
  y = c(0.2, 1.1, 1.5, 0.9, 
        2.1, 1.9, 2.75, 3.4, 
        5.15, 4.6, 4.75, 4.15, 
        7, 6.7, 6.7, 6.95,  
        7, 5.45, 6.15, 6.4, 
        0.001, 0.001, 0.5, 
        0.001, 0.001, 0.001, 0.001, 0.001)
)
head(df)

以下拟合模型:

fun <-with(df,  
 y ~ Yopt*((x-Tmin)/(Topt-Tmin))^(b1*(Topt-Tmin)/(Tmax-Topt))*((Tmax-x)/(Tmax-Topt))^b1
    )

 starters <- expand.grid(Yopt = seq(4, 8, len = 4),
                         Tmin = seq(0, 5, len = 4), 
                         Topt = seq(15, 25, len = 4),
                         Tmax= seq(28, 38, len = 4),
                         b1 = seq(0, 4, len = 4))

fit <- nls2(fun, start = starters, algorithm = "brute-force")

summary(fit)

with(df, c(plot(y~x))); points(fitted(fit)~I(df$x), pch=19)

with(as.list(coef(fit)),
     curve(
 Yopt*((x-Tmin)/(Topt-Tmin))^(b1*(Topt-Tmin)/(Tmax-Topt))*((Tmax-x) / (Tmax-Topt)) ^ b1,
           add=TRUE, col="red"))

enter image description here

1 个答案:

答案 0 :(得分:1)

您应该认真对待@Roland对with使用的评论。

有更好的方法可以做到这一点,但建立你的代码,我会做这样的事情。

library(ggplot2)
library(reshape2)
df$fitted <- fitted(fit)
df$upper <- df$fitted + 1 #I didn't bother to produce actual confidence band
df$lower <- df$fitted - 1
df <- melt(data = df, id.vars = c("x","upper","lower"))
coef <- coef(fit)
fit.fun <-function(x) coef[1]*((x-coef[2])/(coef[3]-coef[2]))^(coef[5]*(coef[3]-coef[2])/(coef[4]-coef[3]))*((coef[4]-x) / (coef[4]-coef[3])) ^ coef[5]

ggplot(df, aes(x=x)) + geom_point( aes(y=value, color=variable)) +
  geom_segment(aes(x=x, xend=x, y=upper, yend=lower)) +
  stat_function(fun=fit.fun, color="blue")

enter image description here