如何在numpy.histogram中选择箱数?

时间:2017-12-02 11:09:20

标签: python numpy numbers histogram bins

如果我使用matplotlib的直方图,我可以选择容器的数量。 但是如何在numpy的直方图中选择箱数呢?

import matplotlib.pyplot as plt
import numpy as np
array = [1,3,4,4,8,9,10,12]

range = int((max(array)) - min(array))+1
x, bins, patch = plt.hist(array, bins=range)

在这种情况下,范围=箱数=(12-1)+1 = 12

结果如此 x = [1. 0. 1. 2. 0. 0. 0. 1. 1. 1. 1. 0. 1.]

但是numpy的结果是

hist, bin_edges = np.histogram(array, density=False)

numpy = [1 1 2 0 0 0 1 1 1 1] numpy_bin = [1. 2.1 3.2 4.3 5.4 6.5 7.6 8.7 9.8 10.9 12.]

使用numpy时,如何选择bin的数量(= int((max(array)) - min(array))+ 1)

我想要像matplotlib一样的结果

1 个答案:

答案 0 :(得分:1)

Matplotlib正在使用numpys直方图,只需将bins=range作为关键字参数添加到np.histogram

hist, edges = np.histogram(array, bins=range, density=False)

如果range是一个整数,你可以得到range个大小相等的bin。 np.histogram中的bin的默认值为bins='auto',它使用算法来确定bin的数量。详情请见:https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.histogram.html

array = [1,3,4,4,8,9,10,12]
range = int((max(array)) - min(array))+1
x, bins, patch = plt.hist(array, bins=range)

x
array([ 1.,  0.,  1.,  2.,  0.,  0.,  0.,  1.,  1.,  1.,  0.,  1.])

hist, edges = np.histogram(array, bins=range)

hist
array([1, 0, 1, 2, 0, 0, 0, 1, 1, 1, 0, 1], dtype=int64)

bins == edges
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True], dtype=bool)
相关问题