Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A third stacked bar in matplotlib

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

like image 775
Mark Ginsburg Avatar asked Apr 20 '17 21:04

Mark Ginsburg


People also ask

How do I show values in a stacked bar chart in Matplotlib?

DataFrame. plot(kind='bar', stacked=True) , is the easiest way to plot a stacked bar plot. This method returns a matplotlib.


1 Answers

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()

enter image description here

like image 157
ImportanceOfBeingErnest Avatar answered Oct 16 '22 13:10

ImportanceOfBeingErnest