在 R 中绘制 nls 模型的导数

问题描述

我使用了 nls 函数来拟合以下等式

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)

现在我已经将模型预测值与观察值相对于 x 绘制为

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

现在我怎么能有下面的情节

enter image description here

数据

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 来获得模型预测的良好图:

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

plot(df)
lines(newdata)

enter image description here

接下来,我们取 x 尺度的对数并计算 dy / dlog(x) 的简单近似数值导数(注意这可以通过改变我们的 {{ x) 中的 1}} 序列:

newdata

所以现在我们可以在对数刻度上绘制您的拟合曲线:

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

enter image description here

还有这样的导数:

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

enter image description here