Juan C
Juan C

Reputation: 6132

Subplot function not showing all subplots

I've been trying to turn my plots into functions so I can reutilize them. Now, I'm trying to graph subplots, where each subplot graphs a category's sales over time. In its loop form, it looks like this:

Categories=dfs['Category'].unique()
fig, ax=plt.subplots(figsize=(18,10))

for j,i in zip(Equipos,range(len(Equipos))):
    df0=dfs.loc[dfs['Category']==j]
    df_aux=df0.groupby(['Date'], as_index=False).sum()
    plt.subplot(3,5,i+1)
    plt.plot( df_aux['Date'], df_aux['Sales'])

plt.show()

Category has 14 values, so this brings a 3x5 grid, without a graph in the last cell. But when I turned that into a function like this one:

def subplots_category(cat,measure,df=dfs,w=18,h=10):
    fig, ax=plt.subplots(figsize=(18,10))

    for j,i in zip(df[cat].unique(),range(len(cat))):
        df0=dfs.loc[dfs[cat]==j]
        df_aux=df0.groupby(['Date'], as_index=False).sum()
        plt.subplot(3,5,i+1)
        plt.plot( df_aux['Date'], df_aux[measure])

    plt.show()

And then input:

subplots_category('Category','Sales')

I get a 2x5 grid, with the last one not appearing (9 graphs). Any idea what could be happening? (Simplified and translated actual code, so, if needed I can post actual code) Thanks in advance !

Edit: After dropping NaNs, the function respects the subplot grid, but still I'm getting less graphs than supposed to.

Upvotes: 0

Views: 418

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339102

The string 'Category' has 8 characters. You loop over the length of this string and hence get 8 subplots.

I would guess that instead you want to loop over all unique categories.

for i, j in enumerate(df[cat].unique()):

Upvotes: 1

Casey Shoup
Casey Shoup

Reputation: 33

If I had to guess it is based on the minimum value of your variable i. Is the minimum value 0? If it isn't then you are starting the subplot at an offset location. If the minimum value of i is, let's say 1, then your first subplot would be like

subplot(3,5,2)

and at the second allocated subplot grid space rather than the first as desired. Also, check what your max value of i is. If you are effectively displaying 10 (9 with 1 empty) then your value of i might not be iterating to what you would expect in order to get 15 plots (14 with 1 empty). I had a similar situation that you are running into and checking my values of i as it is iterated helped me. Hope this helps!

edit: I should note that checking the values of j would be helpful as well.

(This is also my first answer to a question, so if answer formatting is weird then I apologize)

Upvotes: 0

Related Questions