繁体   English   中英

如何将高斯法线与直方图匹配?

[英]How to match a Gaussian normal to a histogram?

我想知道是否有一种好方法可以将高斯法线与 numpy 数组np.histogram(array, bins)形式的直方图相匹配。

如何将这样的曲线绘制在同一图形上并根据直方图调整高度和宽度?

您可以使用高斯(即正态)分布拟合直方图,例如使用 scipy 的 curve_fit。 我在下面写了一个小例子。 请注意,根据您的数据,您可能需要找到一种方法来对拟合 (p0) 的起始值进行正确的猜测。 较差的起始值可能会导致拟合失败。

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

def fit_func(x,a,mu,sigma,c):
    """gaussian function used for the fit"""
    return a * norm.pdf(x,loc=mu,scale=sigma) + c

#make up some normally distributed data and do a histogram
y = 2 * np.random.normal(loc=1,scale=2,size=1000) + 2
no_bins = 20
hist,left = np.histogram(y,bins=no_bins)
centers = left[:-1] + (left[1] - left[0])

#fit the histogram
p0 = [2,0,2,2] #starting values for the fit
p1,_ = curve_fit(fit_func,centers,hist,p0,maxfev=10000)

#plot the histogram and fit together
fig,ax = plt.subplots()
ax.hist(y,bins=no_bins)
x = np.linspace(left[0],left[-1],1000)
y_fit = fit_func(x, *p1)
ax.plot(x,y_fit,'r-')
plt.show()

高斯拟合直方图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM