【问题标题】:Plotting only one side of gaussian in Python using matplotlib and scipy使用 matplotlib 和 scipy 在 Python 中仅绘制高斯的一侧
【发布时间】: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


    【解决方案1】:

    显然,您的数据不太适合或不容易适合高斯函数。您使用p0 = [1,1,1] 的默认初始猜测,这与curve_fit 在开始之前放弃的任何最佳选择相去甚远(检查popt=[1,1,1]pcov=[inf, inf, inf] 的值)。你可以尝试更好的猜测(例如p0 = [2,0, 2000]),但在我的系统上它不会收敛:Optimal parameters not found: Number of calls to function has reached maxfev = 800.

    为了适应“半高斯”,不要浮动中心位置x0(让它等于0):

    def gaus(x,a,sigma):
        return a*exp(-(x)**2/(2*sigma**2))
    
    p0 = [1.2, 4000]
    popt,pcov = curve_fit(gaus,x,y,p0=p0) 
    

    除非您有特殊原因想要拟合高斯,否则为什么不对多项式进行更稳健的线性最小二乘拟合,例如:

    pfit = np.polyfit(x, y, 3)
    poly = np.poly1d(pfit)
    

    【讨论】:

    • 谢谢,我知道它看起来不像高斯,但它肯定像高斯的右边部分。我想问如果可能的话,是否有一种方法可以只将这些数据集拟合到半高斯。
    • @PsJain 啊,好的 - 我已经编辑为您提供了执行此操作的方法。
    • 现在效果很好!非常感谢您快速准确的回复!
    猜你喜欢
    • 2016-12-09
    • 1970-01-01
    • 2019-08-14
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2011-02-10
    • 2021-05-18
    相关资源
    最近更新 更多