【问题标题】:How to match a Gaussian normal to a histogram?如何将高斯法线与直方图匹配?
【发布时间】:2020-07-03 05:16:49
【问题描述】:

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

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

【问题讨论】:

标签: python numpy matplotlib scipy scipy-optimize


【解决方案1】:

您可以使用高斯(即正态)分布拟合直方图,例如使用 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()

【讨论】:

    猜你喜欢
    • 2017-11-23
    • 1970-01-01
    • 2021-12-20
    • 2017-09-16
    • 2022-12-13
    • 1970-01-01
    • 2011-11-03
    • 2010-09-30
    • 1970-01-01
    相关资源
    最近更新 更多