Reputation: 59
I currently have three dictionaries that have the same keys but have different values since they are for three different years. I am trying to create a comparison between the years. I was wondering how I could go about plotting all three graphs on the same axis. I have the following code
import pandas as pd
dt = {'2018':nnum.values, '2019':nnum2.values, '2020':nnum3.values,}
df1=pd.DataFrame(dt,index=nnum.keys())
df1.plot.bar()
I am trying to do something along this line since each dictionary contains the same keys but I keep getting an error. Is there anyway to set the index to the keys of the dictionary without having to type it out manually
Upvotes: 1
Views: 40
Reputation: 862671
Add ()
for values, convert to lists in dictionary dt
for dictionary of lists:
nnum = {1:4,5:3,7:3}
nnum2 = {7:8,9:1,1:0}
nnum3 = {0:7,4:3,8:5}
dt = {'2018': list(nnum.values()), '2019':list(nnum2.values()), '2020':list(nnum3.values())}
df1=pd.DataFrame(dt,index=nnum.keys())
print(df1)
2018 2019 2020
1 4 8 7
5 3 1 3
7 3 0 5
df1.plot.bar()
EDIT: If there is different length of dictionaries and need new values filled by 0
is possible use:
nnum = {1:4,5:3,7:3}
nnum2 = {7:8,9:1,1:0}
nnum3 = {0:7,4:3}
from itertools import zip_longest
L = [list(nnum.values()), list(nnum2.values()), list(nnum3.values())]
L = list(zip_longest(*L, fillvalue=0))
df1 = pd.DataFrame(L,index=nnum.keys(), columns=['2018','2019','2020'])
print(df1)
2018 2019 2020
1 4 8 7
5 3 1 3
7 3 0 0
Upvotes: 1