3
votes

I have used nls function to fit the following equation

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

My code looks as follows

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)

Now I have plotted the model predicted values with the observed values against x as

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

Now how can I have the following plot enter image description here

Data

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
))
1
Can we see dput(df) or a good chunk of it?Allan Cameron
@AllanCameron Sorry for that. Now I have provided the data in dput() format. Please have a look at it.Bappa Das
Thanks for that. Nice to have a reproducible example.Allan Cameron

1 Answers

3
votes

We can first get a good plot of your model prediction by creating a smooth range of values in x and passing that to newdata:

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

plot(df)
lines(newdata)

enter image description here

Next, we take the log of the x scale and calculate a simple approximate numerical derivative for dy / dlog(x) (note this can be made arbitrarily accurate by changing the density of our x sequence in 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

So now we can plot your fitted curve on the log scale:

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

enter image description here

And the derivative like this:

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

enter image description here