1

I am trying to plt Matplotlib stacked bar plot using following code:

import pandas as pd
import matplotlib.pyplot as plt

categories={'Chemistry': 5, 'Literature': 7, 'Medicine': 7, 'Peace': 5, 'Physics': 4, 'Economics': 2}

countries={'USA': {'Chemistry': 57, 'Literature': 9, 'Medicine': 74, 'Peace': 19, 'Physics': 70, 'Economics': 47}, 
'United Kingdom': {'Chemistry': 22, 'Literature': 6, 'Medicine': 26, 'Peace': 5, 'Physics': 22, 'Economics': 7}, 
'Germany': {'Chemistry': 23, 'Literature': 4, 'Medicine': 18, 'Peace': 5, 'Physics': 19, 'Economics': 1},
'France': {'Chemistry': 10, 'Literature': 11, 'Medicine': 12, 'Peace': 9, 'Physics': 8, 'Economics': 3},
'Sweden': {'Chemistry': 5, 'Literature': 7, 'Medicine': 7, 'Peace': 5, 'Physics': 4, 'Economics': 2}}

width=0.5
keys=list(categories.keys())
labels=list(countries.keys())


#Creating nested list with categories
catgr=[]
for category_key in categories:
    k=[]
    for country_key in countries:
        k.append(countries[country_key][category_key])
    catgr.append(k)


#Plotting chart
fig, ax = plt.subplots()
for i in range(len(catgr)):
    ax.bar(labels, catgr[i], width, label=keys[i])

ax.set_ylabel('Prizes won')
ax.set_title('Prizes won by category and country')
ax.legend()
plt.show()

But for some reason, it cuts out some categories (like peace) for USA and other countries, as shown on the picture enter image description here

Any ideas how to tackle it? Thanks!

bjornsing
  • 322
  • 6
  • 25
alex337d
  • 53
  • 1
  • 1
  • 9

1 Answers1

1

The bars now are drawn all starting from zero, so you only see the highest. To obtain stacked bars, plt.bar has an argument bottom= telling where to start each bar. This bottom has to be the sum of the heights of all previous bars.

The simplest way to make the summations is using numpy, which can add arrays element wise. The code then looks like:

import numpy as np

bottom = 0
for i in range(len(catgr)):
    ax.bar(labels, catgr[i], width, bottom=bottom, label=keys[i])
    bottom += np.array(catgr[i])

resulting plot

JohanC
  • 71,591
  • 8
  • 33
  • 66