Вопрос

I have 5 points (x,y) and used matplotlib's histogram2d function to create a heatmap showing different colors denoting the density of each bin. How could I obtain the frequency of the number of points in the bins?

    import numpy as np
    import numpy.random
    import pylab as pl
    import matplotlib.pyplot as plt

    x = [.3, -.3, -.3, .3, .3]
    y = [.3, .3, -.3, -.3, -.4]

    heatmap, xedges, yedges = np.histogram2d(x, y, bins=4)
    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

    plt.clf()
    plt.imshow(heatmap, extent=extent)
    plt.show()

    pl.scatter(x,y)
    pl.show()

Thus, using 4 bins, I would expect the frequencies in each bin to be .2, .2, .2, and .4

Это было полезно?

Решение

you're using 4x4 = 16 bins. If you want four total bins, use 2x2:

In [45]: np.histogram2d(x, y, bins=2)
Out[45]: 
(array([[ 1.,  1.],
       [ 2.,  1.]]),
 array([-0.3,  0. ,  0.3]),
 array([-0.4 , -0.05,  0.3 ]))

You can specify the full shape of the output with a tuple: bins=(2,2)

If you want to normalize the output, use normed=True:

In [50]: np.histogram2d(x, y, bins=2, normed=True)
Out[50]: 
(array([[ 1.9047619 ,  1.9047619 ],
       [ 3.80952381,  1.9047619 ]]),
 array([-0.3,  0. ,  0.3]),
 array([-0.4 , -0.05,  0.3 ]))

Другие советы

heatmap, xedges, yedges = np.histogram2d(x, y, bins=4)
heatmap /= heatmap.sum()

In [57]: heatmap, xedges, yedges = np.histogram2d(x, y, bins=4)

In [58]: heatmap
Out[58]: 
array([[ 1.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 2.,  0.,  0.,  1.]])

In [59]: heatmap /= heatmap.sum()

In [60]: heatmap
Out[60]: 
array([[ 0.2,  0. ,  0. ,  0.2],
       [ 0. ,  0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0. ,  0. ],
       [ 0.4,  0. ,  0. ,  0.2]])

Note that if you use normed=True, then heatmap.sum() in general will not equal 1, rather, the heatmap multiplied by the area of the bin sums to 1. That makes heatmap a distribution, but they are not exactly the frequencies you requested.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top