【问题标题】:Obtain frequencies in each bin for histogram2d获取 histogram2d 的每个 bin 中的频率
【发布时间】:2014-04-11 05:41:41
【问题描述】:

我有 5 个点 (x,y) 并使用 matplotlib 的 histogram2d 函数创建一个热图,显示不同的颜色表示每个 bin 的密度。如何获得 bin 中点数的频率?

    import numpy as np
    import numpy.random
    import pylab as pl
    import matplotlib.pyplot as plt

    x = [.3, -.3, -.3, .3, .3]
    y = [.3, .3, -.3, -.3, -.4]

    heatmap, xedges, yedges = np.histogram2d(x, y, bins=4)
    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

    plt.clf()
    plt.imshow(heatmap, extent=extent)
    plt.show()

    pl.scatter(x,y)
    pl.show()

因此,使用 4 个 bin,我希望每个 bin 中的频率为 .2、.2、.2 和 .4

【问题讨论】:

  • 注意一下,这里不需要导入pylab,使用plt.scatter和plt.show即可
  • 感谢提醒!

标签: python matplotlib histogram2d


【解决方案1】:

您使用的是 4x4 = 16 个垃圾箱。如果您想要总共四个垃圾箱,请使用 2x2:

In [45]: np.histogram2d(x, y, bins=2)
Out[45]: 
(array([[ 1.,  1.],
       [ 2.,  1.]]),
 array([-0.3,  0. ,  0.3]),
 array([-0.4 , -0.05,  0.3 ]))

您可以使用元组指定输出的完整形状:bins=(2,2)

如果你想标准化输出,使用normed=True:

In [50]: np.histogram2d(x, y, bins=2, normed=True)
Out[50]: 
(array([[ 1.9047619 ,  1.9047619 ],
       [ 3.80952381,  1.9047619 ]]),
 array([-0.3,  0. ,  0.3]),
 array([-0.4 , -0.05,  0.3 ]))

【讨论】:

  • 非常感谢您的帮助!
【解决方案2】:
heatmap, xedges, yedges = np.histogram2d(x, y, bins=4)
heatmap /= heatmap.sum()

In [57]: heatmap, xedges, yedges = np.histogram2d(x, y, bins=4)

In [58]: heatmap
Out[58]: 
array([[ 1.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 2.,  0.,  0.,  1.]])

In [59]: heatmap /= heatmap.sum()

In [60]: heatmap
Out[60]: 
array([[ 0.2,  0. ,  0. ,  0.2],
       [ 0. ,  0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0. ,  0. ],
       [ 0.4,  0. ,  0. ,  0.2]])

请注意,如果您使用normed=True,那么heatmap.sum() 通常不等于1,而是heatmap 乘以bin 的面积总和为1。这使得@ 987654326@ 一个分布,但它们不是您要求的频率。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 2011-05-20
    相关资源
    最近更新 更多