Python ProgrammingPython Programming

How to choose bins in Matplotlib histogram?

If you just want them equally distributed, you can simply use range

import numpy as np
import matplotlib.pyplot as plt

# Data in numpy array
data = np.array([12, 15, 13, 20, 19, 20, 11, 19, 11, 12, 19, 13, 
                    12, 10, 6, 19, 3, 1, 1, 0, 4, 4, 6, 5, 3, 7, 
                    12, 7, 9, 8, 12, 11, 11, 18, 19, 18, 19, 3, 6, 
                    5, 6, 9, 11, 10, 14, 14, 16, 17, 17, 19, 0, 2, 
                    0, 3, 1, 4, 6, 6, 8, 7, 7, 6, 7, 11, 11, 10, 
                    11, 10, 13, 13, 15, 18, 20, 19, 1, 10, 8, 16, 
                    19, 19, 17, 16, 11, 1, 10, 13, 15, 3, 8, 6, 9, 
                    10, 15, 19, 2, 4, 5, 6, 9, 11, 10, 9, 10, 9, 
                    15, 16, 18, 13])

# Plot the distribution of numpy data
ax = plt.hist(data, bins=np.arange(min(data), max(data) + 0.25, 0.25), align='left')
# Add axis labels
plt.xlabel("Year")
plt.ylabel("Salary")
plt.title("Example of Histogram Plot")

plt.show()


Choose bins in Histogram
ax = plt.hist(data, bins=np.arange(min(data), max(data) + 0.5, 0.5), align='left')


Choose bins in Histogram
ax = plt.hist(data, bins=np.arange(min(data), max(data) + 1, 1), align='left')


Choose bins in Histogram