如何规范化直方图

时间:2011-08-08 12:48:09

标签: python histogram logarithm

我有这个直方图,它在等间距间隔的数据库中对数组“d”进行计数。

 max_val=np.log10(max(d))
 min_val=np.log10(min(d))
 logspace = np.logspace(min_val, max_val, 50) 


 hist(d,bins=logspace,label='z='+str(redshift),histtype='step')
 show()

问题在于我希望它被规范化,因为该区域是一个。使用选项Normed = True我没有得到结果,可能是因为我使用了对数箱。因此,我尝试以这种方式对直方图进行标准化:

 H=hist(d,bins=logspace,label='z='+str(redshift),histtype='step')
 H_norm=H[0]/my_norm_constant

但后来我不知道如何绘制H_norm与bins的对比

2 个答案:

答案 0 :(得分:2)

我尝试了normed = True,区域是1:

from pylab import *
d = np.random.normal(loc=20, size=10000)
max_val=np.log10(max(d))
min_val=np.log10(min(d))
logspace = np.logspace(min_val, max_val, 50) 


r = hist(d,bins=logspace,histtype='step', normed=True)
print "area":, sum(np.diff(r[1])*r[0])

可以运行代码,并检查输出。如果不是1,请检查您的numpy版本。运行代码时收到此警告消息:

C:\ Python26 \ lib \ site-packages \ matplotlib \ axes.py:7680:UserWarning:             此版本修复了NumPy直方图中的规范化错误             版本1.5之前的函数,发生不均匀             箱宽。返回和绘制的值现在是密度:                 n /(N * bin宽度),             其中n是bin计数,N是总点数。

自己绘制图表:

step(r[1][1:], r[0]/my_norm_constant)

答案 1 :(得分:1)

这使用标准化bin高度的公共标准化,无论bin宽度如何,都可以加1。

import matplotlib
import numpy as np

x = [0.1,0.2,0.04,0.05,0.05,0.06,0.07,0.11,0.12,0.12,0.1414,\
     0.1415,0.15,0.12,0.123,0,0.14,0.145,0.15,0.156,0.12,0.15,\
     0.156,0.166,0.151,0.124, 0.12,0.124,0.12,0.045,0.124]

weights = np.ones_like(x)/float(len(x))
p=plt.hist(x,
    bins=4,
    normed=False, 
    weights=weights,
    #histtype='stepfilled',
    color=[0.1,0.4,0.3]
)

plt.ylim(0,1)
plt.show()

resulting histogram plot: