J.Dillinger
J.Dillinger

Reputation: 56

Python:get data from nested dict to draw a bar

I'm trying to get data from a dict like this:

d= { 
'1992': 
{ 'j': 2048, 'f': 1290, 'm': 3221, 'a': 6994, 'ma': 2091, 'ju': 688, 'jl': 981, 'ag': 2389, 's': 3010, 'o': 13006, 'n': 10477, 'd': 6022 },
'1998': 
{ 'j': 1751, 'f': 1056, 'm': 2664, 'a': 3091, 'ma': 1088, 'ju': 1215, 'jl': 699, 'ag': 2108, 's': 1799, 'o': 4522, 'n': 7200, 'd': 5614 }}

and continue with this pattern: ('year(x)':{'month1':value(1),...month(n):value(n))}

and visualize them in an bar that has in the x axis the list of months, and in the y axis the year. I tried using the Dataframe solution from Python dict to DataFrame Pandas but I cannot apply to the graph. Matplotlib allows me to insert only one 'year':

plt.bar(range(len(d)), d.values(), fill=False)

so i guess Pandas 'Dataframe' is better. Is there a way to get these data in the same bar?

Upvotes: 0

Views: 597

Answers (1)

jezrael
jezrael

Reputation: 863741

It seems you need DataFrame.plot.bar:

df = pd.DataFrame(d)
df.plot.bar()

If want also set order of months:

names = ['j', 'f', 'm', 'a', 'ma','ju', 'jl', 'ag', 's',  'o', 'n', 'd']
df = pd.DataFrame(d).reindex(names)

print (df)
     1992  1998
j    2048  1751
f    1290  1056
m    3221  2664
a    6994  3091
ma   2091  1088
ju    688  1215
jl    981   699
ag   2389  2108
s    3010  1799
o   13006  4522
n   10477  7200
d    6022  5614

graph

Upvotes: 1

Related Questions