Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-scale the counts in a matplotlib histogram

I have a matplotlib histogram that works fine.

hist_bin_width = 4
on_hist = plt.hist(my_data,bins=range(-100, 200,hist_bin_width),alpha=.3,color='#6e9bd1',label='on')

All I want to do is to rescale by a factor of, say, 2. I don't want to change the bin width, or to change the y axis labels. I want to take the counts in all the bins (e.g. bin 1 has 17 counts) and multiply by 2 so that bin 1 now has 34 counts in it.

Is this possible?

Thank you.

like image 694
user1551817 Avatar asked Mar 04 '23 17:03

user1551817


1 Answers

As it's just a simple rescaling of the y-axis, this must be possible. The complication arises because Matplotlib's hist computes and draws the histogram, making it difficult to intervene. However, as the documentation also notes, you can use the weights parameter to "draw a histogram of data that has already been binned". You can bin the data in a first step with Numpy's histogram function. Applying the scaling factor is then straightforward:

from matplotlib import pyplot
import numpy

numpy.random.seed(0)
data = numpy.random.normal(50, 20, 10000)
(counts, bins) = numpy.histogram(data, bins=range(101))

factor = 2
pyplot.hist(bins[:-1], bins, weights=factor*counts)
pyplot.show()
like image 164
john-hen Avatar answered Mar 06 '23 23:03

john-hen