簡體   English   中英

R:用x的每個預測值的置信區間繪制擬合模型

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

如何為每個預測值(以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"))

在此處輸入圖片說明

您應該認真對待@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")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM