Fix Python – Bin size in Matplotlib (Histogram)

Question

Asked By – Sam Creamer

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?

Now we will see solution for issue: Bin size in Matplotlib (Histogram)


Answer

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))

This question is answered By – CodingCat

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0