Plot dictionary of dictionaries in one barplot

Viewed 9536

I've got a dictionary that looks like this

d = {
    'a' : {'L1':2, 'L2':5, 'L3':8},
    'b' : {'L1':4, 'L2':7, 'L3':10},
    'c' : {'L1':19, 'L2':0, 'L3':1},
}

I would like to have a plot where the x axis contains my keys and each key has 3 barplots that correspond to the values of L1, L2 and L3.
All in all, my plot would contain 9 bars grouped by the key (so 3 groups of 3 bars).

So far, what I could do was convert my dictionary to a dataframe and then use seaborn's barplot for each of the keys but that leaves my with 3 different plots.

Is it possible to have one plot with all the informations ?

Many thanks.

2 Answers

You can use pandas, i.e:

import matplotlib.pyplot as plt
import pandas as pd

d = {
    'a': {'L1':2, 'L2':5, 'L3':8},
    'b': {'L1':4, 'L2':7, 'L3':10},
    'c': {'L1':19, 'L2':0, 'L3':1},
}
pd.DataFrame(d).plot(kind='bar')
plt.show()

Output:

output

In your case you need dict keys in x-axis so you can use

pd.DataFrame(d).T.plot(kind='bar')

For those looking for a solution without Pandas, seaborn can also plot dictionaries. All you need is to rearrange the dictionary to match the seaborn data format:

import seaborn as sb

d = {
    'x':    ['L1', 'L1',  'L1', 'L2', 'L2', 'L2', 'L3', 'L3', 'L3'],
    'y':    [   2,    4,   19,     5,    7,    0,    8,    10,   1],
    'group':[  'a',  'b', 'c',   'a',  'b',  'c',   'a',  'b',  'c']
}

sb.barplot(x='x', y='y', hue="group", data=d)

enter image description here

Note that barplot automatically groups both x and group fields. For example, replacing L3 with L2,

d = {
    'x':    ['L1', 'L1',  'L1', 'L2', 'L2', 'L2', 'L2', 'L2', 'L2'],
    'y':    [   2,    4,   19,     5,    7,    0,    8,    10,   1],
    'group':[  'a',  'b', 'c',   'a',  'b',  'c',   'a',  'b',  'c']
}

we get:

enter image description here

Related