Bin size in Matplotlib (Histogram)

Sam Creamer picture Sam Creamer · Aug 8, 2011 · Viewed 274.2k times · Source

I'm using matplotlib to make a histogram.

Is there any way to manually set the size of the bins as opposed to the number of bins?

Answer

CodingCat picture CodingCat · Aug 29, 2012

Actually, it's quite easy: instead of the number of bins you can give a list with the bin boundaries. They can be unequally distributed, too:

plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100])

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

plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth))

Added to original answer

The above line works for data filled with integers only. As macrocosme points out, for floats you can use:

import numpy as np
plt.hist(data, bins=np.arange(min(data), max(data) + binwidth, binwidth))