将半高斯曲线/归一化拟合到数据点

时间:2016-11-18 16:14:25

标签: python matplotlib normalization curve-fitting gaussian

所以我有两个数据列表,我可以在散点图中绘制,如下:

from matplotlib import pyplot as plt
x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
y = [22.4155688819,22.3936180362,22.3177538001,22.1924849792,21.7721194577,21.1590235248,20.6670446864,20.4996957642,20.4260953411,20.3595072628,20.3926201626,20.6023149681,21.1694961343,22.1077417713,23.8270366414,26.5355924353,31.3179807276,42.7871637946,61.9639549412,84.7710953311]

plt.scatter(degrees,RMS_one_image)

这会给你一个看起来像高斯分布的图,这应该是好的,Data to plot

然而,我的问题是我试图将高斯分布拟合到这个,并因为a而失败。它只有半个高斯而不是一个完整的,而b。我之前使用的只使用过一堆数字。如下所示:

# best fit of data
num_bins = 20
(mu, sigma) = norm.fit(sixteen)

y = mlab.normpdf(num_bins, mu, sigma)

n, bins, patches = plt.hist(deg_array, num_bins, normed=1, facecolor='blue', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')

这种方法在这方面是否有效,或者我是否完全以错误的方式解决这个问题?感谢...

1 个答案:

答案 0 :(得分:1)

您的正常解决方案似乎是直接找到数据的期望值和标准差,而不是使用最小二乘拟合。这是使用scipy.optimize中的curve_fit的解决方案。

from matplotlib import pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

x = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19])
y = [22.4155688819,22.3936180362,22.3177538001,22.1924849792,21.7721194577,21.1590235248,20.6670446864,20.4996957642,20.4260953411,20.3595072628,20.3926201626,20.6023149681,21.1694961343,22.1077417713,23.8270366414,26.5355924353,31.3179807276,42.7871637946,61.9639549412,84.7710953311]

# Define a gaussian function with offset
def gaussian_func(x, a, x0, sigma,c):
    return a * np.exp(-(x-x0)**2/(2*sigma**2)) + c

initial_guess = [1,20,2,0]
popt, pcov = curve_fit(gaussian_func, x, y,p0=initial_guess)

xplot = np.linspace(0,30,1000)
plt.scatter(x,y)
plt.plot(xplot,gaussian_func(xplot,*popt))

plt.show()