【问题标题】:Un-normalized Gaussian curve on histogram直方图上的非归一化高斯曲线
【发布时间】:2013-07-22 03:04:16
【问题描述】:

当绘制为直方图时,我有高斯形式的数据。我想在直方图上绘制一条高斯曲线,看看数据有多好。我正在使用 matplotlib 中的 pyplot。我也不想标准化直方图。我可以进行规范化拟合,但我正在寻找非规范化拟合。这里有人知道怎么做吗?

谢谢! 阿比纳夫·库马尔

【问题讨论】:

标签: python matplotlib histogram gaussian


【解决方案1】:

举个例子:

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。需要一些练习才能理解,但它是一个非常强大的工具。

【讨论】:

  • 我们可以根据您上面显示的匹配度检索 a、b 和 c 吗?我想检查一下我的预期。
  • 这正是popt。你会注意到在得到y_fit 我已经完成了f(x_fit, *popt) 这是一个将popt 的元组解包到f 的参数中的技巧。有关更多信息,请参阅文档。
【解决方案2】:

我知道的一篇旧帖子,但想为此贡献我的代码,这只是“按区域修复”的技巧:

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-')

【讨论】:

    【解决方案3】:

    另一种方法是找到归一化拟合并将正态分布乘以(bin_width*数据总长度)

    这会使你的正态分布不正常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多