Kieran Hunt
Kieran Hunt

Reputation: 1838

How do I plot stacked histograms side by side in matplotlib?

I'm looking to plot two side-by-side stacked histograms (similar to the example image below) in matplotlib. I've tried several variations on

bins = np.arange(10)
a1,b1,c1 =plt.hist([arr1,arr2,arr3],bins,stacked=True)
a2,b2,c2 =plt.hist([arr4,arr5,arr6],bins,stacked=True)

But can't seem to avoid getting the second plot to directly overlay the first. Any ideas on how this could be resolved?

Stacked side-by-side histogram example

Upvotes: 2

Views: 5194

Answers (1)

snake_charmer
snake_charmer

Reputation: 3013

The picture shows a bar chart and not a histogram. I am pointing this out, not only because I am an obnoxious pedant, but also because I believe it could help you find the right tool :-)
Indeed, for your purpose plt.bar is probably a better pick than plt.hist.

Based on Scironic's suggestion, I modified this demonstration example to make stacked bars, like the ones on your figure.

Adding an offset to the position index (first argument in plt.bar()) is what prevents the bars from overlapping each other.

import numpy as np
import matplotlib.pyplot as plt

N = 5
men1 = (130, 90, 70, 64, 55)
men2 = (120, 85, 62, 50, 53)
men3 = (100, 70, 60, 45, 50)

ind = np.arange(N) + .15 # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, men1, width, color='g') 
rects2 = ax.bar(ind, men2, width, color='r') 
rects3 = ax.bar(ind, men3, width, color='b')

women4 = (140, 90, 78, 65, 50)
women5 = (130, 80, 70, 60, 45)
women6 = (120, 60, 60, 55, 44)

xtra_space = 0.05
rects2 = ax.bar(ind + width + xtra_space , women1, width, color='orange') 
rects2 = ax.bar(ind + width + xtra_space, women2, width, color='cyan') 
rects2 = ax.bar(ind + width + xtra_space, women3, width, color='purple')

# add some text for labels, title and axes ticks
ax.set_ylabel('Population, millions')
ax.set_title('Population: Age Structure')

ax.set_xticks(ind+width+xtra_space)
ax.set_xticklabels( ('USA', 'Brazil', 'Russia', 'Japan', 'Mexico') )

plt.show()

enter image description here

Upvotes: 5

Related Questions