Incorrect installation using nls function

When I try to fit exponential decay and my x-axis is decimal, the fit is never correct. Here's my details below:

exp.decay = data.frame(time,counts)
   time counts
1   0.4   4458
2   0.6   2446
3   0.8   1327
4   1.0    814
5   1.2    549
6   1.4    401
7   1.6    266
8   1.8    182
9   2.0    140
10  2.2    109
11  2.4     83
12  2.6     78
13  2.8     57
14  3.0     50
15  3.2     31
16  3.4     22
17  3.6     23
18  3.8     20
19  4.0     19
20  4.2      9
21  4.4      7
22  4.6      4
23  4.8      6
24  5.0      4
25  5.2      6
26  5.4      2
27  5.6      7
28  5.8      2
29  6.0      0
30  6.2      3
31  6.4      1
32  6.6      1
33  6.8      2
34  7.0      1
35  7.2      2
36  7.4      1
37  7.6      1
38  7.8      0
39  8.0      0
40  8.2      0
41  8.4      0
42  8.6      1
43  8.8      0
44  9.0      0
45  9.2      0
46  9.4      1
47  9.6      0
48  9.8      0
49 10.0      1

fit.one.exp <- nls(counts ~ A*exp(-k*time),data=exp.decay, start=c(A=max(counts),k=0.1))
plot(exp.decay, col='darkblue',xlab = 'Track Duration (seconds)',ylab = 'Number of Particles', main = 'Exponential Fit')
lines(predict(fit.one.exp), col = 'red', lty=2, lwd=2) 

      

I always get this weird shape. It seems to me that the fit does not recognize the right x-axis, because when I use a different dataset, only integers on the x-axis (time) work fine! I don't understand why this is different from different units.

enter image description here

+3


source to share


1 answer


You need a little modification:

lines(predict(fit.one.exp), col = 'red', lty=2, lwd=2)

      

it should be

lines(exp.decay$time, predict(fit.one.exp), col = 'red', lty=2, lwd=2)

      

This way you will make sure to plot against the desired abscissa values.



I tested it like this:

data = read.csv('exp_fit_r.csv')

A0 <- max(data$count)
k0 <- 0.1

fit <- nls(data$count ~ A*exp(-k*data$time), start=list(A=A0, k=k0), data=data)

plot(data)
lines(data$time, predict(fit), col='red')

      

which gives me the following output:

enter image description here

As you can see, fitting describes the actual data very well, it is simply a matter of plotting the correct abscissa values.

+2


source







All Articles