matplotlib直方图中"counts"和"number of observations"的区别

Difference between "counts" and "number of observations" in matplotlib histogram

matplotlib.pyplot.hist() 文档将参数 "density"(其弃用名称为 "normed")描述为:

density : bool, optional

If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1. This is achieved by dividing the count by the number of observations times the bin width and not dividing by the total number of observations.

元组的第一个元素指的是 y 轴值。它说它通过以下方式设法使直方图下的 area 为 1:count 除以 观察次数 bin 宽度的倍数。

计数观察次数有什么区别?在我看来,它们是同一件事:变量值落入某个 bin 的实例数(或计数数或观察数)。但是,这意味着每个 bin 的转换后计数仅超过 bin 宽度(因为 # / #*bin_width = 1/bin_width),这没有任何意义。

有人可以为我澄清一下吗?感谢您的帮助,对于这个可能很愚蠢的问题深表歉意。

所有观察的计数就是观察的次数。但是对于直方图,您对每个 bin 的计数 感兴趣。因此,对于每个 bin,您将此 bin 的计数除以观察总数乘以 bin 宽度。

import numpy as np

observations = [1.2, 1.5, 1.7, 1.9, 2.2, 2.3, 3.6, 4.1, 4.2, 4.4]
bin_edges = [0,1,2,3,4,5]

counts, edges = np.histogram(observations, bins=bin_edges)
print(counts)   # prints [0 4 2 1 3]

density, edges = np.histogram(observations, bins=bin_edges, density=True)
print(density)  # prints [0.  0.4 0.2 0.1 0.3]

# calculate density manually according to formula
man_density = counts/(len(observations)*np.diff(edges))
print(man_density)   # prints [0.  0.4 0.2 0.1 0.3]

# Check that density == manually calculated density
assert(np.all(man_density == density))

我认为文档中的措辞有点混乱。计数是给定 bin 中的条目数(bin 的高度),观察数是进入直方图的事件总数。

文档对它们如何规范化进行了区分,因为通常有两种方法可以进行规范化:

  • count / number of observations - 在这种情况下,如果您将输出数组的所有条目相加,您将得到 1.
  • count / (number of observations * bin width) - 在这种情况下,输出数组的 积分 1,因此它是真实的概率密度。这就是 matplotlib 所做的,他们只是想清楚这一区别。