简体   繁体   中英

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

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

在此处输入图像描述

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

在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM