2016-11-18 119 views
0

所以我有數據,我可以在散點圖中繪製的兩份名單,因爲這樣的:擬合半高斯曲線/標準化的數據點

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

但我的問題是我想嘗試適合高斯分佈到此,並失敗悲慘,因爲一個。它只是高斯的一半而不是完整的一個,而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--') 

這種方法是否在這裏工作,或者我完全用錯誤的方式去解決這個問題?謝謝...

+0

由於我們不知道'norm.fit'是什麼,我們無法提供幫助。這裏是,創建一個[最小完整的可驗證示例](http://stackoverflow.com/help/mcve)。 – ImportanceOfBeingErnest

回答

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() 
+0

做了一些小調整。非常感謝! :) – kb3hts