簡體   English   中英

plt.hist()vs 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 應該使用相同的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.histnumpy.histogram工作方式相同,但您不能將從numpy.histogram獲得的數據numpy.histogramplt.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM