[英]Gaussian fit in Python plot
I am trying to fit Gaussian function to my Python plot.我正在尝试将高斯函数拟合到我的 Python 图中。 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这是我文件的链接: 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. gauss
拟合函数必须使用numpy
数组。 math
functions can't provide this functionality, they work with scalars. math
函数无法提供此功能,它们与标量一起使用。 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.
难怪 fit 函数不收敛。
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.其实还有第三个问题,你计算的mean/sigma是错误的,但是因为你的数据不能服从高斯分布,所以我们暂时可以忽略这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.