3

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
))
UseR10085
  • 7,120
  • 3
  • 24
  • 54

1 Answers1

3

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

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • thank you for your answer. Can you tell me why the derivative is coming in negative? – UseR10085 Dec 21 '20 at 15:18
  • @BappaDas The line that nls fits to your points has a downsloping gradient throughout its range, so the derivative is negative. If you look at the data you supplied, it can only really have a negative gradient. Are you sure your data isn't reversed or negated? – Allan Cameron Dec 21 '20 at 15:23
  • I think the `nls` should have been done with logx rather than only x. I think then the derivative plot may become positive. Another thing, how can I have a equation for the minimum point of the derivative curve. – UseR10085 Dec 21 '20 at 15:37
  • 1
    @BappaDas no, plotting y against log x still gives a downward sloping plot. The result in my answer looks like the one in your question but rotated 180 degrees. I think perhaps dy / d -log(x) would give you the same shape?. – Allan Cameron Dec 21 '20 at 15:45