Matplotlib histogram2d标准化不等于1

时间:2012-07-11 16:18:52

标签: python python-3.x matplotlib

有一天,我无法理解正在发生的事情。我有一个工具,它从X,Y,Z坐标的数组(Numpy数组)生成2D直方图(Z在一分钟内不重要)。我需要将结果标准化,以便我可以进行进一步的计算。但是,当使用normed = True命令时,数组的总和总是在0.000006左右。

我希望对整个直方图进行标准化,因此所有数组元素都会加起来1.将normed设置为False会正确返回bin中的样本数,但显然这不是规范化的。我用3k元素的阵列测试它一直到30k仍然是同样的问题。为了记录,我的数据包括所有3个轴上的负坐标。

代码如下:

def histogrammer(coords):      # coords is a 3D numpy array

H, xedges, yedges = np.histogram2d(coords[:,0], coords[:,1], bins=(50, 50), range=([-10000.0,10000.0],[-10000.0,10000.0]), normed=True)
H.shape, xedges.shape, yedges.shape
extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]]

global displayHistograms
if displayHistograms == True:
    print('Displaying:')
    plt.imshow(H, extent=extent, interpolation='nearest')
    plt.colorbar()
    plt.show()

print('{0:.30f}'.format(np.sum(H)))    # Debug normalisation

return H

我为两个数组运行此代码,生成两个不同的直方图。每个的打印声明:

0.000006250000000000000299510850
0.000006250000000000002840609692

有人可以告诉我哪里出错吗?在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

normed=True将音量(即binarea*binheight之和)标准化为1,而不是高度之和。因为这是通常对直方图进行标准化的方式,因为标准化直方图是概率密度函数的估计。

如果你想将高度之和加1,只需将非标准化值除以总点数:

H, xedges, yedges = np.histogram2d(coords[:,0], coords[:,1], bins=(50, 50), range=([-10000.0,10000.0],[-10000.0,10000.0]))
H_normalized = H/float(coords.shape[0])

答案 1 :(得分:0)

设置normed = True会给出bin密度,而不是bin中总项目的分数。您需要从箱宽度或手动计算。

相关问题