How do I create a complete bar chart with numpy?
I have a very long list of c numpy.array
. I want to create a histogram for it. However, Numpy's built-in bar chart requires a predetermined number of bins. What is the best way to generate a complete histogram with one bin for each value?
+2
source to share
2 answers
If you have an array of integers and the maximum value is not too large, you can use numpy.bincount:
hist = dict((key,val) for key, val in enumerate(numpy.bincount(data)) if val)
Edit: If you have floating point data or data spread over a huge range, you can convert it to integers by doing:
bins = numpy.unique(data)
bincounts = numpy.bincount(numpy.digitize(data, bins) - 1)
hist = dict(zip(bins, bincounts))
+8
source to share