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.
2条答案
按热度按时间9w11ddsr1#
plt.hist
的返回值为:返回:元组:(n,bin,patches)或([n0,n1,...],bin,[patches0,patches1,...])
因此,您需要做的就是适当地捕获返回值。例如:
返回的
bins
定义了所使用的每个bin的边缘。hgc7kmma2#
使用
np.histogram
将值分箱到plt.hist
中的离散区间,因此如果出于某种原因,您需要不绘制数据的箱和计数,则可以使用np.histogram
。如果您想要数据和图,如@Bonlenfum所示,hist()
调用已经返回了这样的数据。从下面可以看到,pyplot和numpy直方图的计数和bin完全匹配。