Search code examples
rplotnls

R: Plotting fitted model with the confident intervals for each predicted values in x


How could I plot the fitted model with the confident intervals for each predicted value (in x= 5, 10, 15, 20, 25, 30, 35) ?

For the next dataset

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)

And the follow fitted model:

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


Solution

  • You should take @Roland's comment on your use of with seriously.

    There are much better ways of doing this, but building on your code, I would have done something like this.

    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