gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:24:41 24 4
gpt4 key购买 nike

下面几行

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

enter image description here

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

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

enter image description here

根据我对 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。为什么这没有反射(reflect)在直方图中——为什么两条尾部都没有两个大尖峰?

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

enter image description here

但是,您可以使用 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')

enter image description here

关于python - plt.hist() vs np.histogram() - 意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46656010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com