当绘制为直方图时,我有高斯形式的数据。我想在直方图上绘制一条高斯曲线,看看数据有多好。我正在使用matplotlib的pyplot。另外,我不想标准化直方图。我可以做标准拟合,但我正在寻找一个非标准化的拟合。这里有人知道怎么做吗?
谢谢! 阿比纳夫·库马尔
答案 0 :(得分:7)
举个例子:
import pylab as py
import numpy as np
from scipy import optimize
# Generate a
y = np.random.standard_normal(10000)
data = py.hist(y, bins = 100)
# Equation for Gaussian
def f(x, a, b, c):
return a * py.exp(-(x - b)**2.0 / (2 * c**2))
# Generate data from bins as a set of points
x = [0.5 * (data[1][i] + data[1][i+1]) for i in xrange(len(data[1])-1)]
y = data[0]
popt, pcov = optimize.curve_fit(f, x, y)
x_fit = py.linspace(x[0], x[-1], 100)
y_fit = f(x_fit, *popt)
plot(x_fit, y_fit, lw=4, color="r")
这将使高斯图符合分布,您应该使用pcov
给出一个数量,以确定拟合的好坏程度。
确定数据的高斯或任何分布的更好方法是Pearson chi-squared test。需要一些练习来理解它,但它是一个非常强大的工具。
答案 1 :(得分:4)
我知道的一篇旧帖子,但是想要为此做出贡献,这只是“按区域修复”技巧:
from scipy.stats import norm
from numpy import linspace
from pylab import plot,show,hist
def PlotHistNorm(data, log=False):
# distribution fitting
param = norm.fit(data)
mean = param[0]
sd = param[1]
#Set large limits
xlims = [-6*sd+mean, 6*sd+mean]
#Plot histogram
histdata = hist(data,bins=12,alpha=.3,log=log)
#Generate X points
x = linspace(xlims[0],xlims[1],500)
#Get Y points via Normal PDF with fitted parameters
pdf_fitted = norm.pdf(x,loc=mean,scale=sd)
#Get histogram data, in this case bin edges
xh = [0.5 * (histdata[1][r] + histdata[1][r+1]) for r in xrange(len(histdata[1])-1)]
#Get bin width from this
binwidth = (max(xh) - min(xh)) / len(histdata[1])
#Scale the fitted PDF by area of the histogram
pdf_fitted = pdf_fitted * (len(data) * binwidth)
#Plot PDF
plot(x,pdf_fitted,'r-')
答案 2 :(得分:3)
另一种方法是找到标准化拟合并将正态分布乘以(bin_width *数据总长度)
这将使您的正态分布不正常化