![](/img/trans.png)
[英]What is the difference between `np.histogram` and `plt.hist`? Why don't these commands plot the same graphics?
[英]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
值, b1
和b2
的值相同
然后我單獨使用pyplot
創建一個圖(使用bins=auto
應該使用相同的np.histogram()
函數 ):
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
為每個倉起始值的列表,並且counts
是值的每一個倉的相應的數字。 如上面的直方圖所示,這應該產生幾乎完美的正態分布,但是,如果調用print(counts, bins)
counts
結果顯示第一個和最后一個分箱具有相當大的~11,000個數。 為什么這不會反映在直方圖中 - 為什么兩條尾部都沒有兩個大的尖峰?
編輯2
這只是一個分辨率問題,我的情節看起來太小了,兩端的尖峰都無法正確渲染。 放大允許它們顯示。
您假設plt.hist
可以區分包含計數值的數組和包含要計數的 值的數組。
然而,這並非發生的情況,當您將計數傳遞給plt.hist
,它將計算它們並將它們放在提供的箱中。 這可能導致空的直方圖,但也會導致奇怪的直方圖。
因此,雖然plt.hist
和numpy.histogram
工作方式相同,但您不能將從numpy.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
陰謀vizualize通過獲得直方圖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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.