如何选择 numpy.histogram 中的 bin 数量?

How to choose number of bins in numpy.histogram?

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

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. 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 时,如何选择 bins(= int((max(array)) - min(array))+1)

我想要和matplotlib一样的结果

Matplotlib 使用 numpys 直方图,传递 bin 数只需将 bins=bin_range 作为关键字参数添加到 np.histogram:

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

如果 bin_range 是整数,您将获得 bin_range 数量的相同大小的垃圾箱。 np.histogram 中 bins 的默认值是 bins='auto',它使用算法来决定 bins 的数量。阅读更多:https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.histogram.html

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

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

hist, edges = np.histogram(array, bins=bin_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)