【问题标题】:Normalize histogram2d by bin area按 bin 区域归一化 histogram2d
【发布时间】:2015-10-18 15:58:03
【问题描述】:

我有一个用 numpy 生成的二维直方图:

H, xedges, yedges = np.histogram2d(y, x, weights=mass * (1.0 - pf),
                                   bins=(yrange,xrange))

请注意,我目前正在使用质量函数对垃圾箱进行称重(mass 是一个 numpy 数组,其尺寸与xy 相同)。这些 bin 是对数的(通过 xrange = np.logspace(minX, maxX, 100) 生成)。

但是,我真的想通过质量函数对垃圾箱进行加权,但将它们归一化(即除以)每个垃圾箱的面积:例如- 每个垃圾箱都有xrange[i] * yrange[i] 的区域。但是,由于xrangeyrange 的尺寸与massxy 的尺寸不同……我不能简单地将标准化放在np.histogram2d 调用中。

如何按每个日志箱中的面积标准化箱数?

作为参考,这里是绘图(我添加了 x 和 y 1D 直方图,我还需要按 bin 的宽度进行归一化,但是一旦我弄清楚如何为 2D 做它应该是类似的) .

仅供参考 - 我使用 matplotlib 生成主要(和轴直方图):

X,Y=np.meshgrid(xrange,yrange)
H = np.log10(H)
masked_array = np.ma.array(H, mask=np.isnan(H))  # mask out all nan, i.e. log10(0.0)
cax = (ax2dhist.pcolormesh(X,Y,masked_array, cmap=cmap, norm=LogNorm(vmin=1,vmax=8)))

【问题讨论】:

    标签: python arrays numpy matplotlib


    【解决方案1】:

    我想你只是想将normed=True 传递给np.histogram2d

    规范bool,可选

    如果False,则返回每个 bin 中的样本数。如果True,则返回bin密度bin_count / sample_count / bin_area


    如果您想手动计算 bin 区域并进行标准化,最简单的方法可能是使用broadcasting

    x, y = np.random.rand(2, 1000)
    xbin = np.logspace(-1, 0, 101)
    ybin = np.logspace(-1, 0, 201)
    
    # raw bin counts
    counts, xe, ye = np.histogram2d(x, y, [xbin, ybin])
    
    # size of each bin in x and y dimensions
    dx = np.diff(xbin)
    dy = np.diff(ybin)
    
    # compute the area of each bin using broadcasting
    area = dx[:,  None] * dy
    
    # normalized counts
    manual_norm = counts / area / x.shape[0]
    
    # using normed=True
    counts_norm, xe, ye = np.histogram2d(x, y, [xbin, ybin], normed=True)
    
    print(np.allclose(manual_norm, counts_norm))
    # True
    

    【讨论】:

    • 天哪……就这么简单吗?!我会尝试发布结果。谢谢。
    • 是的...我认为可以。谢谢你也展示了广播方法......实际上我需要在标准化中使用另一个变量(整个模拟的体积......所以我可以标准化为“每单位体积”。所以这个提示会派上用场!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2019-10-21
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多