从直方图函数获取 bin 信息

问题描述 投票:0回答:2

我正在使用 matplotlib 在 python 中绘制直方图:

plt.hist(nparray, bins=10, label='hist')

是否可以打印包含所有容器信息的数据框,例如每个容器中的元素数量?

python matplotlib plot histogram
2个回答
48
投票

plt.hist
的返回值为:

返回:元组:(n, bins, patch) 或 ([n0, n1, ...], bins, [补丁0,补丁1,...])

因此您需要做的就是适当地捕获返回值。例如:

import numpy as np
import matplotlib.pyplot as plt

# generate some uniformly distributed data
x = np.random.rand(1000)

# create the histogram
(n, bins, patches) = plt.hist(x, bins=10, label='hst')

plt.show()

# inspect the counts in each bin
In [4]: print n
[102  87 102  83 106 100 104 110 102 104]

# and we see that the bins are approximately uniformly filled.
# create a second histogram with more bins (but same input data)
(n2, bins2, patches) = plt.hist(x, bins=20, label='hst')

In [34]: print n2
[54 48 39 48 51 51 37 46 49 57 50 50 52 52 59 51 58 44 58 46]

# bins are uniformly filled but obviously with fewer in each bin.

返回的

bins
定义了所使用的每个 bin 的边缘。


0
投票

将值分入

plt.hist
中的离散区间是使用
np.histogram
完成的,因此,如果由于某种原因您想要分箱和计数而不绘制数据,则可以使用
np.histogram
。如果您想要将数据与绘图一起使用,如 @Bonlenfum 所示,则
hist()
调用已经返回此类数据。

从下面可以看到,计数和 bin 与 pyplot 和 numpy 直方图完全匹配。

x = np.random.rand(1000)
n_bins = 100

# plot histogram
n_plt, bins_plt, patches = plt.hist(x, n_bins)
# compute histogram
n_np, bins_np = np.histogram(x, n_bins)

(n_plt == n_np).all() and (bins_plt == bins_np).all()  # True
© www.soinside.com 2019 - 2024. All rights reserved.