jameslyns
jameslyns

Reputation: 29

Building a stacked bar chart from a list within a dictionary matplotlib

I have a dictionary which contains a list for each value, for example:

countries = {'NG': [1405, 7392], 'IN': [5862, 9426], 'GB': [11689, 11339], 'ID': [7969, 2987]}

Is there a way to build a stacked bar chart from this dictionary using each value as a bit of the stack for each key?

Upvotes: 1

Views: 4989

Answers (3)

Kewl
Kewl

Reputation: 3417

Here's an example of doing a bar chart with the data you've given. We just loop through the items in the dictionary. Sum them up and plot a bar for the value (this will be the top-most part of the bar chart). Then plot the bottom part second - this will plot it 'on top of' the summed value.

import matplotlib.pyplot as plt

cols = [u'#348ABD', u'#A60628']

d = {'NG': [1405, 7392], 'IN': [5862, 9426], 'GB': [11689, 11339], 'ID': [7969, 2987]}

i = 0
for key,vals in d.items():
    plt.bar(left=i, height=sum(vals), color=cols[0])
    plt.bar(left=i, height=vals[0], color=cols[1])
    i = i + 1

plt.xticks(range(len(d)), d.keys())

Which produces

enter image description here

Upvotes: 0

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339220

As in the bar_stacked example from the matplotlib site, use the bottom argument to bar to shift the bars, one on top of the other.

import matplotlib.pyplot as plt
import numpy as np

countries = {'NG': [1405, 7392], 'IN': [5862, 9426], 
             'GB': [11689, 11339], 'ID': [7969, 2987]}

c = []
v = []             
for key, val in countries.items():
    c.append(key)
    v.append(val)
v = np.array(v)

plt.bar(range(len(c)), v[:,0])
plt.bar(range(len(c)), v[:,1], bottom=v[:,0])
plt.xticks(range(len(c)), c)
plt.show()

enter image description here

Upvotes: 1

Diziet Asahi
Diziet Asahi

Reputation: 40697

Have a look at the documentation for Axes.bar.

This function takes an argument bottom= which defines the bottom level of each bar. In your case, you have to call bar() twice, once for the first set of values (and an implied value of bottom=0, which I set explicitly here to highlight the difference) and a second time with the second set of values and bottom equal to the first set. That way, the second set of bars rests on top of the first set.

countries = {'NG': [1405, 7392], 'IN': [5862, 9426], 'GB': [11689, 11339], 'ID': [7969, 2987]}

plt.bar(range(len(countries)), np.array(list(countries.values()))[:,0], bottom=0, align='center')
plt.bar(range(len(countries)), np.array(list(countries.values()))[:,1], bottom=np.array(list(countries.values()))[:,0], align='center')
plt.xticks(range(len(countries)), countries.keys())
plt.show()

enter image description here

Upvotes: 0

Related Questions