Home > Software design >  Get the middle of all bins from plt.hist
Get the middle of all bins from plt.hist

Time:12-22

I have made a histogram with plt.hist() and I now have an array with the bins in this form:

bins = [0, 1, 2, 3, 4, 5] # n edges

Is there a easy way to get the middle from these bins? End result would be a list with n - 1 centers like:

centers = [0.5, 1.5, 2.5, 3.5, 4.5] # n - 1 centers

I don't know beforehand what the bins will be.

CodePudding user response:

This seems to work good enough:

x = np.array([0, 1, 2, 3, 4, 5, 6])
y = [(x[i]   x[i   1]) / 2 for i in range(len(x[:-1]))]
print(y)
# [0.5, 1.5, 2.5, 3.5, 4.5, 5.5]

CodePudding user response:

In [136]: bins = np.array([0, 1, 2, 3, 4, 5])

In [137]: centers = 0.5*(bins[:-1]   bins[1:])

In [138]: centers
Out[138]: array([0.5, 1.5, 2.5, 3.5, 4.5])
  • Related