Search code examples
matplotlibhistogram

matplotlib stacked plot not working as expected


enter image description hereI am trying to use matplotlib's hist function to make stacked plots. Here is what my code block looks like:

a = np.array([5.2, 6.7, 8.9, 10.5, 4.2, 2.1])
b = np.array([3.1, 2.2, 9.9, 15.5, 3.8, 1.4])
fig,ax = plt.subplots(1,1,figsize=(7,7))
values = np.arange(0, 6, 1)

plt.hist(values, weights=a,bins=5, histtype='barstacked', label='a')
plt.hist(values, weights=b, bins=5, histtype='barstacked',label='b')
plt.legend()
plt.show()

I also tried histtype='bar' but that also doesn't seem to work. I must be missing something very obvious here, but the two hists are clearly not stacked.

Any help would be appreciated.


Solution

  • Try using bottom parameter with the output from first histogram, note the return, the n element, of plt.hist:

    g = plt.hist(values, weights=a, bins=5, label='a')
    plt.hist(values, weights=b, bins=5, label='b', bottom=g[0])
    

    Output:

    enter image description here