簡體   English   中英

在 R 中繪制 nls model 的導數

[英]Plotting derivative of nls model in R

我已經使用nls function 來擬合以下等式

y ~ (C + (A1*exp(-x/h1)) + (A2*exp(-x/h2)))

我的代碼如下所示

f <- as.formula(y ~ (C + (A1*exp(-x/h1)) + (A2*exp(-x/h2))))
nls_b <- nls(f, data = df, start = list(C = 0.140, A1 = 0.051, h1 = 586.772, A2 = 0.166, h2 = 33.323))
summary(nls_b)
b_opt <- predict(nls_b, newdata=df)

現在我已經將 model 預測值與 x 的觀測值繪制為

plot(y=df$y, x=df$x)
lines(y=b_opt, x=df$x, type='l')

現在我怎樣才能擁有以下 plot 在此處輸入圖像描述

數據

df = structure(list(x = c(2L, 5L, 10L, 33L, 50L, 100L, 500L, 1500L
), y = c(0.34272, 0.34256, 0.30483, 0.25772, 0.21584, 0.19295, 
0.16144, 0.144)), class = "data.frame", row.names = c(NA, -8L
))

我們首先可以通過在x中創建平滑的值范圍並將其傳遞給newdata來獲得 model 預測的良好 plot :

newdata <- data.frame(x = seq(1, 1500, 1))
newdata$y <- predict(nls_b, newdata)

plot(df)
lines(newdata)

在此處輸入圖像描述

接下來,我們取 x 尺度的對數並計算dy / dlog(x)的簡單近似數值導數(注意,這可以通過改變newdatax序列的密度來任意精確):

newdata$logx <- log(newdata$x)
newdata$dlogx <- c(0, diff(newdata$logx))
newdata$dy <- c(0, diff(newdata$y))
newdata$dy_dlogx <- newdata$dy / newdata$dlogx

所以現在我們可以 plot 您在對數刻度上的擬合曲線:

with(newdata, plot(logx, y, type = "l"))

在此處輸入圖像描述

像這樣的導數:

with(newdata, plot(logx, dy_dlogx, type = "l", col = "red"))

在此處輸入圖像描述

暫無
暫無

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

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