如何计算二维直方图的总体积?

How to calculate the total volume of a 2D Histogram?

对于 Python 相对较新,尤其是将其用于统计目的的新手,深表歉意。我从 excel 中读取了两列数据。我为每一列创建了 1D 直方图,并证明它们下面的面积等于 1,如下所示:

n, bins, _=plt.hist(thickness, 15, range=[0,8], density=True)
Area_T= sum(numpy.diff(bins)*n)

现在我想证明二维直方图的面积等于 1。我制作了二维直方图,只是不知道如何整合它,因为它 returns 是一个二维数组。

h, xedges, yedges, _=plt.hist2d(thickness_data, height_data, bins=(20,20), density=True)

您可以通过将 h 中的每个值与其对应的 bin 的宽度和高度相乘来计算总体积:

import matplotlib.pyplot as plt
import numpy as np

h, xedges, yedges, _ = plt.hist2d(np.random.randn(1000).cumsum(), np.random.randn(1000).cumsum(), 
                                  bins=(20, 30), density=True)
total_volume = np.sum(h * np.diff(xedges).reshape(-1, 1) * np.diff(yedges).reshape(1, -1))
print("total_volume =", total_volume) # prints "total_volume = 1.0"

没有density=True的直方图的体积是一个bin的大小乘以样本数。所有 bin 的宽度为 xedges[-1]-xedges[0]。身高是yedges[-1]-yedges[0]。一个 bin 的面积是所有 bin 的面积除以 bin 的数量(示例中的20*30=600)。

import matplotlib.pyplot as plt
import numpy as np

h, xedges, yedges, _ = plt.hist2d(np.random.randn(1000).cumsum(), np.random.randn(1000).cumsum(),
                                  bins=(20, 30), density=False)
total_volume = np.sum(h * np.diff(xedges).reshape(-1, 1) * np.diff(yedges).reshape(1, -1))
print("total volume :", total_volume)
print("   predicted :", (xedges[-1] - xedges[0]) * (yedges[-1] - yedges[0]) / 600 * 1000)

例如打印:

total volume : 4057.2494712526022
   predicted : 4057.2494712526036

所以,只是一个非常小的舍入误差。