Get center of bins histograms python

3.5k Views Asked by At

I'm using the hist2d function of matplotlib.pyplot, giving it input some coordinates (x,y).

I would like, after having defined the histogram, to get the center of each bin, i.e., the coordinates of the center of each bin.

Is there an easy way to get them?

1

There are 1 best solutions below

0
tdy On BEST ANSWER

The return values of plt.hist and plt.hist2d include bin edges, so take the mean of the left edges and right edges:

  • plt.hist

    h, xedges, patches = plt.hist(x)
    xcenters = (xedges[:-1] + xedges[1:]) / 2
    
  • plt.hist2d

    h, xedges, yedges, image = plt.hist2d(x, y)
    xcenters = (xedges[:-1] + xedges[1:]) / 2
    ycenters = (yedges[:-1] + yedges[1:]) / 2
    

Note that you can use numpy functions if preferred, though I find it less readable in this case:

xcenters = np.mean(np.vstack([xedges[:-1], xedges[1:]]), axis=0)

Full example with plt.hist2d:

import matplotlib.pyplot as plt
import numpy as np

x = np.random.random(50)
y = np.random.random(50)

h, xedges, yedges, image = plt.hist2d(x, y, bins=5)

xcenters = (xedges[:-1] + xedges[1:]) / 2
ycenters = (yedges[:-1] + yedges[1:]) / 2

Output:

>>> xedges
# array([0.01568168, 0.21003078, 0.40437988, 0.59872898, 0.79307808, 0.98742718])

>>> xcenters
# array([0.11285623, 0.30720533, 0.50155443, 0.69590353, 0.89025263])

>>> yedges
# array([0.00800735, 0.20230702, 0.39660669, 0.59090636, 0.78520603, 0.97950570])

>>> ycenters
# array([0.10515718, 0.29945685, 0.49375652, 0.68805619, 0.88235586])