plt.hist() 与 np.histogram() - 意想不到的结果

plt.hist() vs np.histogram() - unexpected results

下面几行

a1, b1, _ = plt.hist(df['y'], bins='auto')
a2, b2 = np.histogram(df['y'], bins='auto')

print(a1 == a2)
print(b1 == b2)

等于 a1 的所有值等于 a2 的值,b1b2

的值相同

然后我单独使用 pyplot 创建一个图(使用 bins=auto should use the same np.histogram() function):

plt.hist(df['y'], bins='auto')
plt.show()

然后我尝试实现相同的直方图,但是我自己调用 np.histogram(),并将结果传递给 plt.hist(),但我得到一个空白直方图:

a2, b2 = np.histogram(df['y'], bins='auto')
plt.hist(a2, bins=b2)
plt.show()

根据我对 plt.hist(df['y'], bins='auto') 的理解,我创建的这两个图应该完全相同 - 为什么我使用 Numpy 的方法不起作用?

编辑

根据下面@MSeifert 的回答,我相信

counts, bins = np.histogram(df['y'], bins='auto')

bins 是每个 bin 的起始值列表,counts 是每个 bin 中对应的值数。如上面的直方图所示,这应该会产生近乎完美的正态分布,但是,如果调用 print(counts, bins) the result of counts 显示第一个和最后一个 bin 的数量相当大,约为 11,000。为什么这没有反映在直方图中——为什么两条尾部都没有两个大尖峰?

编辑 2

这只是一个分辨率问题,我的地块似乎太小以至于两端的尖峰无法正确呈现。放大允许它们显示。

您假设 plt.hist 可以区分包含 作为值的数组 和包含 包含作为值的值的数组 .

然而,事实并非如此,当您将计数传递给 plt.hist 时,它会对它们进行计数并将它们放入提供的箱子中。这可能会导致直方图为空,但也会导致直方图怪异。

因此,虽然 plt.histnumpy.histogram 的工作原理相同,但您不能只将从 numpy.histogram 获得的数据传递给 plt.hist,因为那样会计算值的计数(不是你所期望的):

import numpy as np
import matplotlib.pyplot as plt

%matplotlib notebook

f, ax = plt.subplots(1)
arr = np.random.normal(10, 3, size=1000)
cnts, bins = np.histogram(arr, bins='auto')
ax.hist(cnts, bins=bins)

但是您可以使用 bar 绘图来可视化通过 numpy.histogram:

获得的直方图
f, (ax1, ax2) = plt.subplots(2)
cnts, bins = np.histogram(arr, bins='auto')
ax1.bar(bins[:-1] + np.diff(bins) / 2, cnts, np.diff(bins))
ax2.hist(arr, bins='auto')