簡體   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