【发布时间】:2015-11-26 12:45:16
【问题描述】:
我在第一象限有一组看起来像高斯的点,我试图在 python 中使用高斯拟合它,我的代码如下:
import pylab as plb
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
import math
x=ar([37,69,157,238,274,319,391,495,533,626,1366,1855,2821,3615,4130,4374,6453,6863,7021,
7951,8646,9656,10464,11400])
y=ar([1.77,1.67,1.65,1.17,1.34,1.46,0.75,1,0.8,1.02,0.65,0.69,0.44,0.44,0.55,0.43,0.75,0.27,0.26,
0.44,0.04,0.44,0.26,0.04])
n = 24 #the number of data
mean = sum(x*y)/n #note this correction
sigma = math.sqrt(sum(y*(x-mean)**2)/n) #note this correction
def gaus(x,a,x0,sigma):
return a*exp(-(x-x0)**2/(2*sigma**2))
popt,pcov = curve_fit(gaus,x,y,p0=None, sigma=None) #'''p0=[1,mean,sigma]'''
plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()
输出是:这个图: http://s2.postimg.org/wevggkc95/Workspace_1_022.png
为什么所有的红点都在下面,还要注意我对半高斯感兴趣,因为我的数据就是这样,所以我的 y 值一开始很大,然后像高斯钟的一侧一样减小。谁能告诉我如何在 python 中拟合这条曲线,(以防它不适合高斯)。或者换句话说,我希望代码适合我的点的一半(左侧)高斯(仅在第一象限中)。请注意,我的点不能像我之前尝试的那样拟合成指数递减曲线,并且在较低的“x”值下也不能很好地拟合。
【问题讨论】:
标签: python matplotlib scipy gaussian