2017-07-19 34 views
3

當我嘗試擬合指數衰減並且我的x軸有十進制數時,擬合從不正確。這裏是我的數據如下:使用nls函數進行錯誤擬合

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) 

我總是得到這個怪異的適合。在我看來,這個擬合不能識別正確的x軸,因爲當我使用一組不同的數據時,只有x軸(時間)中的整數才適用!我不明白爲什麼它與不同的單位有所不同。

enter image description here

+0

由於這是您的第一個問題:請不要忘記點擊回答旁邊的綠色支票以獲得有用的答案並接受最好的答案;檢查然後變成綠色 – Cleb

回答

2

你需要一個小的修改:

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

應該

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

這種方式,你一定要暗算所需的值在你的橫座標。

我測試它像這樣:

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') 

這給了我下面的輸出:

enter image description here

正如你所看到的,合適的描述了實際的數據非常好,這只是一個繪製正確的橫座標值的問題。