Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot a histogram with constant bar widths but different bin sizes

I have a Python script which produces a single histogram of three data sets, where the bin sizes are provided as a list. The Python script sippet is as follows:

bin_l=np.arange(0,14,1)
bin_l=np.append(bin_l,max_bin)

plt.hist([wind_plot_o, wind_plot_m, wind_plot_b],bins=bin_l, align='mid',
     label=['label1', 'label2', 'label3'],color=['k','g', 'r'])

Where, the element appended to bin_l later is the maximum of the data given. So the last bin size would be different than other bin sizes.
The above script snippet, along with the rest of the script, produces the following plot:
Histogram Which is good, except for a problem. I need all the bars to be of same size, I do not want the bar sizes to depend upon the bin size, which doesn't look good in my case.
The matplotlib documentation for hist() says the parameter 'rwidth' can be used to adjust the bar width, still relative to the bin size, which is what it is currently doing and of no use to me.
So, how can I keep the bar widths of matplotlib histogram same while using non-uniform bin sizes?

Note: It may look like a duplicate of this post, but it isn't. I am not using logarithmic scale for the X axis.

like image 901
RogUE Avatar asked Oct 23 '25 18:10

RogUE


1 Answers

This is a bit unconventional to do. But plt.hist returns the number of elements in each bin. You can use this data (or from numpy.histogram to skip plotting the original histogram) to create a "bar graph" with equal widths instead.

counts, _, _ = plt.hist(...)
plt.close()                                # Don't want the plot from plt.hist
for n, Y in enumerate(counts):
    X = [n*.3 + x for x in range(len(Y))]  # position bars next to each other
    plt.bar(X, Y, 0.3)
like image 197
busybear Avatar answered Oct 26 '25 09:10

busybear



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!