I want to create a stacked barplot with 3 bars on top of each other. I managed to do this for a 2-bar stacking, but I can't add the 3rd one, any ideas?
I will add some simple example code to show you what I mean:
from matplotlib import pyplot as plt
data1 = [100,120,140]
data2 = [150,120,190]
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,5))
## Absolute count
ax1.bar(range(len(data1)), data1, label='data 1', alpha=0.5, color='b')
ax1.bar(range(len(data2)), data2, bottom=data1, label='data 2', alpha=0.5, color='r')
plt.sca(ax1)
plt.xticks([0.4, 1.4, 2.4], ['category 1', 'category 2', 'category 3'])
ax1.set_ylabel("Count")
ax1.set_xlabel("")
plt.legend(loc='upper left')
## Percent
totals = [i + j for i,j in zip(data1, data2)]
data1_rel = [i / j * 100 for i,j in zip(data1, totals)]
data2_rel = [i / j * 100 for i,j in zip(data2, totals)]
ax2.bar(range(len(data1_rel)), data1_rel, alpha=0.5, color='b')
ax2.bar(range(len(data2_rel)), data2_rel, bottom=data1_rel, alpha=0.5, color='r')
plt.sca(ax2)
plt.xticks([0.4, 1.4, 2.4], ['category 1', 'category 2', 'category 3'])
ax2.set_ylabel("Percentage")
ax2.set_xlabel("")
plt.show()
Now, let's say I want to add, e.g., data3 = [100,150,130]
Intuitively, I would do it like this
ax1.bar(range(len(data3)), data3, bottom=data1+data2, label='data 3', alpha=0.5, color='g')
However, this unfortunately doesn't add the 3rd bar.