r - 在 R 中绘制 nls 模型的导数

标签 r plot derivative 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) 的简单近似数值导数(注意这可以通过改变我们的密度来任意精确 newdata 中的 x 序列):

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

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

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

enter image description here

像这样的导数:

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

enter image description here

关于r - 在 R 中绘制 nls 模型的导数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65393067/

相关文章:

wolfram-mathematica - Mathematica 中四元数范数的导数

r - 如何在R中创建并排的barplot? (-0.01 *高度: non-numeric argument to binary operator)中的错误

r - 绘制来自 SparkR DataFrame 的数据

python - 读取 CSV 并绘制彩色折线图

F# 多项式微分器

java - 在java中使用数组求多项式的导数

R将数据分组

r - R 中的逻辑索引失败

r - 绘制 R 中两个有序列表之间排名变化的最简单方法?

android - 如何在 MPAndroidChart 中为单线图设置不同的样式?