jadenkorr jadenkorr - 3 months ago 40
Python Question

Matplotlib Stacked Histogram Bin Width

When creating a stacked histogram in Matplotlib I noticed that the bin widths shrink. In this simple example:

import numpy as np
import matplotlib
import matplotlib.pylab as plt

#Create histograms and plots
fig = plt.figure()
gs = matplotlib.gridspec.GridSpec(1, 2)
h1 = fig.add_subplot(gs[0])
h2 = fig.add_subplot(gs[1])

x = np.random.normal(0, 5, 500)
y = np.random.normal(0, 20, 500)

bins = np.arange(-60,60, 5)

h1.hist([x, y], bins=bins, stacked=True)
h2.hist(x, bins=bins, alpha=1)
h2.hist(y, bins=bins, alpha=0.5)

plt.tight_layout()
plt.show()
filename = 'sample.pdf'
plt.savefig(filename)


I get the following output:

enter image description here

Notice that the histogram on the left has spacing between each bin even though both the left and right histograms are using the same bins.

Is there a way to correct this behavior? I would like the histogram on the left to use the full bin widths such that neighboring bins share an edge.

Answer

If the first argument of a ax.hist-call is a list of lists (or a 2d numpy-array or a combination of the two) it will automatically make the bins smaller. The rwidth parameter of the ax.hist-call is the parameter that determines the bin-width. Setting it to 1 will do what you want it to do:

h1.hist([x, y], bins=bins, stacked=True, rwidth=1)