matplotlib直方图中“计数”和“观察次数”之间的差异

2024-09-24 22:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

那个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轴值。它说它设法使直方图下的面积为1除以:计数除以观察次数乘以箱子宽度

计数和观察次数之间有什么区别?在我的头脑中,它们是同一件事:实例的数量(或计数的数量或观察的数量)变量值落入某个箱子。但是,这意味着每个箱子的转换计数数只比箱子宽度大一个(因为#/#*箱子宽度=1/箱子宽度),这没有任何意义。你知道吗

有人能帮我澄清一下吗?谢谢你的帮助,很抱歉这个可能很愚蠢的问题。你知道吗


Tags: ofthetonumber数量by宽度matplotlib
2条回答

所有观测的计数是观测的数量。但是用直方图你会对每箱的计数感兴趣。因此,对于每个箱子,你将这个箱子的计数除以观察总数乘以箱子宽度。你知道吗

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))

我认为文件中的措辞有点混乱。计数是给定容器中的条目数(容器高度),观察次数是进入直方图的事件总数。你知道吗

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

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

相关问题 更多 >