从Python中的直方图中获取数据点

时间:2013-11-21 18:19:26

标签: python matplotlib histogram

我制作了一个函数'cdf'(累积分布)的直方图。直方图基本上是计数与亮度的比值。现在,如何从直方图中提取数据点?我需要Luminosities的实际值。 我在Python中使用Matplotlib,任何在线书籍,示例,教程等都无济于事。

l= [ss.gammainccinv(aa+1, u[i]) for i in a] #is the cdf function
plt.hist(l, 50, histtype= 'step', align='mid') #is the histogram
plt.show()

我不确定是否应该将边框与边缘或中间点对齐,但我需要的只是l的列表。

任何建议都将不胜感激!

3 个答案:

答案 0 :(得分:12)

你已经有了l的列表,所以我不确定你最后一句话的意思,所以也许我误解了这个问题。

要从直方图中获取值,plt.hist会返回它们,所以您只需要保存它们。

如果不保存它们,解释器只会打印输出:

In [34]: x = np.random.rand(100)

In [35]: plt.hist(x)
Out[35]: 
(array([ 11.,   9.,  10.,   6.,   8.,   8.,  10.,  10.,  11.,  17.]),
 array([ 0.00158591,  0.100731  ,  0.19987608,  0.29902116,  0.39816624,
        0.49731133,  0.59645641,  0.69560149,  0.79474657,  0.89389165,
        0.99303674]),
 <a list of 10 Patch objects>)

所以,要保存它们,请执行:

counts, bins, bars = plt.hist(x)

答案 1 :(得分:2)

您还可以从已绘制的直方图中检索信息。例如:

x = np.random.rand(100)
plt.hist(x)

enter image description here

ax = plt.gca() # get axis handle

您可以使用 patches 访问每个单独的栏。然后 .get_xy() 会给你单个条的 xy 坐标(左下角),.get_width() 会给你条的宽度,.get_height() 会给你条的高度(这是可能是你想要的)。

p = ax.patches  # There are 10 patches
p[0].get_xy()
>> (0.011714084185001972, 0.0)
p[0].get_width()
>> 0.09871329223828645
p[0].get_height()
>> 8.0

所以要检索所有高度:

heights = [patch.get_height() for patch in p]

并重现直方图:

plt.bar(range(len(heights)), heights)

enter image description here

答案 2 :(得分:0)

如果您想将分配分配给垃圾箱,您可以按照此处说明的以下方式进行Which elements of list go into which histogram bins?

nbins=7
# Some example data
A = np.random.randint(0, 10, 10) 
B = np.random.rand(10)

counts, binEdges=np.histogram(A,bins=nbins)
>>> binEdges, np.digitize(A, binEdges)
array([ 0.        ,  1.28571429,  2.57142857,  3.85714286,  5.14285714,
    6.42857143,  7.71428571,  9.        ])