Reputation: 2269
Consider this example code from matplotlib website:
# a stacked bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, menMeans, width, color='#d62728', yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
bottom=menMeans, yerr=womenStd)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
plt.show()
Suppose I had a third series and I wanted it to be stacked on top. How to express a
bottom
parameter? I tried to simply do
menMeans + womenMeans
but that didn't work.
Source: https://matplotlib.org/2.0.0/examples/pylab_examples/bar_stacked.html
Upvotes: 6
Views: 4741
Reputation: 339200
In principle you are correct: You need to add up the previous bar heights to obtain the bottom
of the next bar.
The problem is that you cannot simply add tuples. So a good idea would be to make them numpy
arrays, menMeans = np.array(menMeans)
.
Those numpy
arrays can easily be added together, such that
p3 = plt.bar(ind, childrenMeans, width, bottom=menMeans+womenMeans)
works out nicely.
Complete code:
import numpy as np
import matplotlib.pyplot as plt
menMeans = np.array((20, 35, 30, 35, 27))
womenMeans = np.array((25, 32, 34, 20, 25))
childrenMeans = np.array((21, 30, 32, 10, 36))
ind = np.arange(5)
width = 0.35
p1 = plt.bar(ind, menMeans, width, color='#d62728', )
p2 = plt.bar(ind, womenMeans, width, bottom=menMeans)
p3 = plt.bar(ind, childrenMeans, width, bottom=menMeans+womenMeans)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0], p3[0]), ('Men', 'Women', "Children"))
plt.show()
Upvotes: 8