matplotlib 直方图中的不对称性

asymmetry in matplotlib histograms

在阅读了我预期的关于直方图的 matplotlib 文档后,该范围忽略了下异常值和上限异常值。

"范围:元组,可选,默认值:None 垃圾箱的下限和上限范围。下异常值和上异常值 被忽略。如果未提供,则 range 为 (x.min(), x.max())。范围 如果 bins 是一个序列则无效。"

看看下面的例子:

import numpy as np
import matplotlib.pyplot as plt

numbers1 = np.arange(1.,101.)
numbers2 = np.arange(0.5,100.5)
numbers3 = np.arange(0,100)

plt.figure(figsize=(12,4))
plt.subplot(1,3,1)
plt.hist(numbers1, bins = 25, range = (25,75), normed=True)
plt.title('numbers1')
plt.ylim((0,0.035))
plt.subplot(1,3,2)
plt.hist(numbers2, bins = 25, range = (25,75), normed=True)
plt.title('numbers2')
plt.ylim((0,0.035))
plt.subplot(1,3,3)
plt.hist(numbers3, bins = 25, range = (25,75), normed=True)
plt.title('numbers3')
plt.ylim((0,0.035))

不幸的是,我无法 post 结果的图像...(没有足够的声誉),但是:numbers1 和 numbers3 的直方图都具有比我预期的值更高的值最后一个箱子。

为什么会这样,真的应该这样吗?我希望所有这些看起来都像中间那个。 :-(

25-75 范围内的所有数字都用于直方图。对于数组 numbers1numbers3,正好是 51 个数字,因为 25 和 75 都包括在内。您将这些数字强制分为 25 个 bin,这意味着将有 24 个高度 2/51 的 bin 和一个高度 3/51 的 bin。 Matplotlib 选择将 73、74 和 75 都放在最后一个 bin 中并使其成为最大的。

对于numbers2,范围内只有50个数字,即25.5到74.5。因此,每个 bin 的高度为 2/50.

您可以看到,对于 numbers1numbers3,当您设置范围 (25, 74.99999)(25.0000001, 75) 时,较高的 bin 消失,因为 25 或 75 是已排除,范围内有 50 个数字。


您可以获得 bin 的限制,因为 plt.hist returns 值、bin 和补丁。所以如果你使用

(n, bins, p) = plt.hist(numbers1, bins = 25, range = (25,75), normed=True)

bins 包含 26 个 bin 限制的数组。所以这是箱子的所有起点加上最后一个箱子的终点。使用这个你可以准确地推断出每个值在哪个 bin 中。