Skip to main content
 首页 » 编程设计

python之按 bin 区域归一化 histogram2d

2024年10月24日19me-sa

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

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

请注意,我目前正在用质量函数称量垃圾箱( mass 是一个与 x 和 y 具有相同维度的 numpy 数组)。箱子是对数的(通过 xrange = np.logspace(minX, maxX, 100) 生成)。

但是,我真的想通过质量函数对 bin 进行加权,但将它们归一化(即除以)每个 bin 的面积:例如- 每个箱子都有面积 xrange[i] * yrange[i] .然而,由于 xrange和 yrange没有与 mass 相同的尺寸, x和 y ...我不能简单地将规范化放在 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))) 

请您参考如下方法:

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

normed: bool, optional

If False, returns the number of samples in each bin. If True, returns the bin density 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