R:使用nls将高斯峰拟合到密度绘图数据

时间:2012-04-19 14:54:45

标签: r

我正在尝试将两个高斯峰拟合到我的密度绘图数据中,使用以下代码:

model <- function(coeffs,x)
{
    (coeffs[1] * exp( - ((x-coeffs[2])/coeffs[3])**2 ))

}

y_axis <- data.matrix(den.PA$y)
x_axis <- data.matrix(den.PA$x)
peak1 <- c(1.12e-2,1075,2) # guess for peak 1
peak2 <- c(1.15e-2,1110,2) # guess for peak 2

peak1_fit <- model(peak1,den.PA$x)
peak2_fit <- model(peak2,den.PA$x)

total_peaks <- peak1_fit + peak2_fit
err <- den.PA$y - total_peaks

fit <- nls(y_axis~coeffs2 * exp( - ((x_axis-coeffs3)/coeffs4)**2 ),start=list(coeffs2=1.12e-2, coeffs3=1075, coeffs4=2))
fit2<- nls(y_axis~coeffs2 * exp( - ((x_axis-coeffs3)/coeffs4)**2 ),start=list(coeffs2=1.15e-2, coeffs3=1110, coeffs4=2))


fit_coeffs = coef(fit)
fit2_coeffs = coef(fit2)

a <- model(fit_coeffs,den.PA$x)
b <- model(fit2_coeffs,den.PA$x)



plot(den.PA, main="Cytochome C PA", xlab= expression(paste("Collision Cross-Section (", Å^2, ")")))
lines(results2,a, col="red")
lines(results2,b, col="blue")

这给了我以下情节:

enter image description here

这是我遇到问题的地方。我相互独立地计算拟合,高斯峰叠加在彼此的顶部。我需要将err变量输入nls,这应该返回6个系数,然后我可以从中重新建模高斯峰以适应绘图。

1 个答案:

答案 0 :(得分:2)

一旦我发布了这个问题,答案就出现了。改变适合:

fit <- nls(y_axis~(coeffs2 * exp( - ((x_axis-coeffs3)/coeffs4)**2)) + (coeffs5 * exp( - ((x_axis-coeffs6)/coeffs7)**2)), start=list(coeffs2=1.12e-2, coeffs3=1075, coeffs4=2,coeffs5=1.15e-2, coeffs6=1110, coeffs7=2))

给出:

enter image description here

一个不优雅的解决方案,但它完成了这项工作。