# How to fit multiple Gaussian peaks to data [duplicate]

How would I fit this data with Gaussian Peaks? I have tried various codes but none have even worked. Note: If I do Log[data], the peaks are more visible

(I have tried the method from here but it got many errors)

• @shrx It did not work, I literally copied and pasted the code and made sure my data was correct format. It works for fake data though which was a smaller size – minusatwelfth Oct 30 '15 at 8:15
• Please post your code and an example of your data - what errors did you get? – shrx Oct 30 '15 at 8:16
• pastebin.com/0G4Nrfci This is my code which worked (the data is faked), but as soon as I replace 'data' with real data from here pastebin.com/aEJAdUuX, it shows many errors. Just copy and paste my code and you will see – minusatwelfth Oct 30 '15 at 8:19
• Your data is very noisy, and I don't see any gaussian peaks other than the large spike near the end of the data. How many peaks do you expect to be there? – shrx Oct 30 '15 at 8:27
• @shrx I don't know how many peaks there are, I'm trying to find that out. Though they are definitely Gaussian – minusatwelfth Oct 30 '15 at 8:30

Your provided data is very noisy. You can get more information from it if you filter it first. I will apply a LowpassFilter and a logarithmic transform on the $y$ values, and scale down the $x$ values. This usually helps the fitting algorithm.

datat = Transpose[{#[[All, 1]]/1500,
Log10[LowpassFilter[#[[All, 2]], .1]]} &@data];
ListPlot[datat, PlotRange -> All, Joined -> True]


Now, you can perform the multi-peak fitting process from the linked discussion.

It's up to you to decide which peaks are signal and which are artifacts. I am providing here the solution with 4 peaks.

With[{n = 4},
resfunc =
peakfunc[A[#], μ[#], σ[#], x] & /@ Range[n] /.
model[datat, n][[2]]]
(* copied from @Silvia's answer with slight modifications *)
Show@{Plot[Evaluate[resfunc], {x, -5, 10},
PlotStyle -> ({Directive[Dashed, Thick,
ColorData["DarkRainbow"][#]]} & /@
Rescale[Range[Length[resfunc]]]), PlotRange -> All,
Frame -> True, Axes -> False, ImageSize -> 700],
Plot[Evaluate[Total@resfunc], {x, -5, 10},
PlotStyle -> Directive[Thick, Red, Opacity[.5]], PlotRange -> All,
Frame -> True, Axes -> False],
Graphics[{PointSize[.003], Gray, Line@datat}]}


You will of course have to scale the fitted functions back to the original data, but this should be trivial.

• there is supposed to be a lot more peaks. have a look at Logarithm of the data and Joined->True. I think silvia's code cannot handle many peaks – minusatwelfth Oct 31 '15 at 5:55