拟合的高斯看起来太低了,因为它适用于所有箱,其中大多数箱为零。一个解决方案是只将高斯函数拟合到非零区间。
我使用
np.histogram
而不是
plt.hist
去拿垃圾桶,但这只是口味问题。重要的部分是
xh
和
yh
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Generate example data
x = np.random.randn(100000) * 50 + 75
x = np.round(x / 10) * 10
x = x[x >= 20]
yhist, xhist = np.histogram(x, bins=np.arange(4096))
xh = np.where(yhist > 0)[0]
yh = yhist[xh]
def gaussian(x, a, mean, sigma):
return a * np.exp(-((x - mean)**2 / (2 * sigma**2)))
popt, pcov = curve_fit(gaussian, xh, yh, [10000, 100, 10])
plt.plot(yhist)
i = np.linspace(0, 300, 301)
plt.plot(i, gaussian(i, *popt))
plt.xlim(0, 300)
P.S.Sigma通常表示标准偏差而不是方差。这就是为什么我在
gaussian
作用