Zen
Zen

Reputation: 83

Gaussian fit in Python plot

I am trying to fit Gaussian function to my Python plot. I have attached the code here. Any corrections would be appreciated!

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import math
import random
from numpy import genfromtxt

data= genfromtxt ('PVC_Cs137.txt')
plt.xlim(0,2500)
plt.ylim(0,30000)
plt.xlabel("Channel number")
plt.ylabel("Counts")

x = data[:,0]
y = data[:,1]

n = len(x)                          
mean = sum(x*y)/n                   
sigma = sum(y*(x-mean)**2)/n    

def gaus(x,a,x0,sigma):
  return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.plot(x,gaus(x,*popt))
plt.show()

And here is the link to my file: https://www.dropbox.com/s/hrqjr2jgfsjs55x/PVC_Cs137.txt?dl=0

Upvotes: 1

Views: 1133

Answers (1)

Mr. T
Mr. T

Reputation: 12410

There are two problems with your approach. One is related to programming. The gauss fit function has to work with a numpy array. math functions can't provide this functionality, they work with scalars. Therefore your fit functions should look like this

def gauss(x, a, x0, sigma):
    return a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2))

This produces with the right mean/sigma combination a Gauss curve like this

enter image description here

And now we look at the distribution of the values from your file:

enter image description here

This doesn't even vaguely look like a Gauss curve. No wonder that the fit function doesn't converge.

Actually there is a third problem, your calculation of mean/sigma is wrong, but since you can't fit your data to a Gaussian distribution, we can neglect this problem for now.

Upvotes: 2

Related Questions