Skip to main content
 首页 » 编程设计

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

2025年01月19日10dflying

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

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 直方图,传递 bins 的数量只需将 bins=bin_range 作为关键字参数添加到 np.histogram:

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

如果 bin_range 是一个整数,您将得到 bin_range 数量的相同大小的 bin。 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)