Scipy curve_fit在我运行代码时未显示数据拟合值

问题描述 投票:1回答:1

我正在使用Scipy curve_fit向数据添加高斯拟合,但是当我运行代码时,拟合不显示,我也不知道为什么!

绘制数据:

def graph(two_theta, counts, metadata):
    fig = plt.semilogy(two_theta, counts, "b.", label="Data")
    plt.ylim(bottom=0.1, top=counts.max()+1000)   
    plt.legend(loc="best", facecolor="c", framealpha=0.1, edgecolor="k")
    plt.show()
    return fig

高斯拟合由以下项定义:

def gaussian(two_theta, I_0, two_theta_0, sigma):                              
    I = (I_0/(sigma*sqrt(2*pi)))*exp(-(two_theta - two_theta_0)**2/(2*sigma**2))
    return I

使用数据找到高斯拟合的最佳参数:

def gaussian_optimization(two_theta, counts):
    peaks = find_peaks(counts, height=100, width=1)
    I_0 = counts[peaks[0]]    
    two_theta_0 = two_theta[peaks[0][0]]
    sigma = peaks[1]["widths"][0]
    return I_0, two_theta_0, sigma

绘制拟合:

def gaussian_fit(two_theta, counts, I_0, two_theta_0, sigma):
    popt, pcov = curve_fit(gaussian, two_theta, counts, p0=[I_0, two_theta_0, sigma]) 
    x_axis = np.linspace(two_theta.min(), two_theta.max(), two_theta.size()*10)  
    y_axis = gaussian(x_axis, *popt)
    fit = plt.plot(x_axis, y_axis, "r-", label="Fit") 
    return fit

仅绘制数据点,而不绘制高斯拟合,帮助!

编辑

很遗憾,我无法共享数据。当我打电话给fit时,它会引发错误:

    File "C:\Users\Anaconda3\lib\site-packages\scipy\optimize\minpack.py", line 396, in leastsq    gtol, maxfev, epsfcn, factor, diag) TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

使用curve_fit之前的断点并在控制台中检查类型,告诉我two_theta,counts,I_0是ndarray类型,two_theta_0和sigma是float64类型。

two_theta和counts数组中元素的数据类型都是float64和two_theta [0]类型,counts [0]按预期返回我的数据集的第一个数据点(浮点数)。

python matplotlib scipy curve-fitting
1个回答
0
投票

[如果您多次调用plt.plot()plt.show(),您将生成多个图,并且绘制适合度后看起来并不像您调用plt.show()。如果您尝试:

popt, pcov = curve_fit(gaussian, two_theta, counts, p0=[I_0, two_theta_0, sigma]) 
x_axis = np.linspace(two_theta.min(), two_theta.max(), two_theta.size()*10)  
y_axis = gaussian(x_axis, *popt)
plt.plot(two_theta, counts, "b.", label="Data")
plt.plot(x_axis, y_axis, "r-", label="Fit")
plt.ylim(0.1, counts.max()+1000) 
plt.yscale('log')
plt.legend()
plt.show()

您应该在同一图中获得数据和拟合度。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.