Skip to content
scipython.com

P6.3.2Plotting a histogram with pyplot.bar

We have seen how to create a histogram plot from an array with pyplot.hist, but suppose you have already created arrays hist and bins using np.histogram and wish to plot the resulting histogram from these arrays. You can't use pyplot.hist because this function expects to act on the original array of data. Use pyplot.bar (documented here; see also Section 7.1.2 of the book) to plot a hist array as a bar-chart.

Show solution

The bar chart needs to be constructed with the entries of hist centred on the corresponding bins, but the bins array contains the bin boundaries:

In [x]: print(bins)
[   0.   20.   40.   60.   80.  100.]

So construct an array containing the bin centres:

In [x]: bin_centres = (bins[:-1] + bins[1:])/2
In [x]: print(bin_centres)
[ 10.  30.  50.  70.  90.]

Then call plt.bar specifying the width of each bin, and centering the bars on the values in bin_centres:

In [x]: import matplotlib.pyplot as plt
In [x]: plt.bar(bin_centres, hist, width=20, align='center')