Hunter Pack
Hunter Pack

Reputation: 11

Looping through a dictionary of lists to plot subplots

I am trying to use matplotlib to plot 10 charts. I have created the figure using the following code:

fig, ax = plt.subplots(5, 2, figsize=(11,11))

I have a dictionary with 10 keys, each containing a dataframe related to that key. I would like to create a subplot for each key, having a barplot for one of the columns in the dataframe. I tried using a for loop like below but can't figure this problem out. Can someone please point me in the right direction?

for key, value in breed_dict.items():
    ax = value.plot(1, 1, kind='bar')

I know this isn't close but I am completely stuck.

Thanks.

Upvotes: 0

Views: 1011

Answers (1)

Sagar
Sagar

Reputation: 404

Let the dictionary be dictOfDF

dictOfDF = { 1:df1 , 2:df2 , ... , 10:df10}

Iterate through the subplots in the following manner:

for i in range(5):
    for j in range(2):
        subplot = ax[i,j]

To access each individual DataFrame, just iterate through the key of the dictOfDF

Now, access each index in the dfAtKey and plot it to the subplot

for ind in dfAtKey.index:
    subplot.bar( dfAtKey.loc[ind,0] , dfAtKey.loc[ind,1] , width = 0.5 )

So, your code should look somewhat like this:

fig = plt.figure()
fig, ax = plt.subplots(5, 2, figsize=(11,11))    

dictOfDF = { 1:df1 , 2:df2 , ... , 10:df10 }

key = 1
for i in range(5):
    for j in range(2):
        subplot = ax[i,j]

        dfAtKey = dictOfDF[key]

        for ind in dfAtKey.index:
            subplot.bar( dfAtkey.loc[ind,0] , dfAtKey.loc[ind,1] , width = 0.5 )

        key += 1

Hope this helps

Upvotes: 1

Related Questions