Reputation: 12587
I'm trying to fit two gaussian peaks to my density plot data, using the following code:
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")
This gives me the following plot:
This is where I have my problem. I calculate the fits independently of each other and gaussian peaks are overlaid on on top of each other. I need to feed the err
variable into nls
which should return 6 coeffs from which I can then re-model the gaussian peaks to fit to the plot.
Upvotes: 1
Views: 3353
Reputation: 12587
The answer came to me as soon as i Posted the question. Changing fit to this:
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))
Gives:
An inelegant soloution but it does the job.
Upvotes: 2