您可以通过将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 的面积是 all 的面积除以 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
所以,只是一个很小的舍入误差。