user2293224
user2293224

Reputation: 2220

Creating multiple plot using for loop from dataframe

I am trying to create a figure which contains 9 subplots (3 x 3). X, and Y axis data is coming from the dataframe using groupby. Here is my code:

fig, axs = plt.subplots(3,3)
for index,cause in enumerate(cause_list):


    df[df['CAT']==cause].groupby('RYQ')['NO_CONSUMERS'].mean().axs[index].plot()
    axs[index].set_title(cause)



plt.show() 

However, it does not produce the desired output. In fact it returned the error. If I remove the axs[index]before plot() and put inside the plot() function like plot(ax=axs[index]) then it worked and produces nine subplot but did not display the data in it (as shown in the figure). enter image description here

Could anyone guide me where am I making the mistake?

Upvotes: 1

Views: 590

Answers (1)

StupidWolf
StupidWolf

Reputation: 46888

You need to flatten axs otherwise it is a 2d array. And you can provide the ax in plot function, see documentation of pandas plot, so using an example:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

cause_list = np.arange(9)

df = pd.DataFrame({'CAT':np.random.choice(cause_list,100),
                  'RYQ':np.random.choice(['A','B','C'],100),
                  'NO_CONSUMERS':np.random.normal(0,1,100)})

fig, axs = plt.subplots(3,3,figsize=(8,6))
axs = axs.flatten()
for index,cause in enumerate(cause_list):

    df[df['CAT']==cause].groupby('RYQ')['NO_CONSUMERS'].mean().plot(ax=axs[index])
    axs[index].set_title(cause)

plt.tight_layout()

enter image description here

Upvotes: 1

Related Questions