3

I want to plot several barplots using matplotlib library (or other libraries if possible), and place each figure in its place using subplot.

I am also using groupby to group by in each category and sum the values. Then I just want to show three columns (Num1, Num2, Num3):

#Build subplot with three rows and two columns
fig, axes = plt.subplots(figsize=(12, 8) , nrows = 3, ncols = 2)
fig.tight_layout()

#five categorical columns and three numerical columns of interest
for i, category in enumerate(['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5']):   
    ax = fig.add_subplot(3,2,i+1)
    data.groupby(category).sum()[['Num1','Num2','Num3']].plot.bar(rot=0)
    plt.xticks(rotation = 90)

What I get are six empty plots arranged in 3rows and 2cols, followed by 5 correct plots arranged in one column one after another. An example of a plots is seen in the photo.

Thanks for your helps and suggestions.

Figure Hereeee

1
  • 1
    Your code is redundant. Either you create the subplots via plt.subplots or you add subplots via fig.add_subplot. Not both. Commented Jan 30, 2019 at 22:54

2 Answers 2

2

When you create a figure using fig, axes = plt.subplots(figsize=(12, 8) , nrows = 3, ncols = 2), you already have initialized all of the subplots with the nrows and ncols keywords. axes is a list you can iterate over during the for loop.

I think everything should work fine if you change:

ax = fig.add_subplot(3,2,i+1)

to:

ax = axes[i]

All together:

fig, axes = plt.subplots(figsize=(12, 8) , nrows = 3, ncols = 2)
fig.tight_layout()

#five categorical columns and three numerical columns of interest
for i, category in enumerate(['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5']):   
    ax = axes[i]
    data.groupby(category).sum()[['Num1','Num2','Num3']].plot.bar(rot=0,ax=ax)
    ax.xticks(rotation = 90)
Sign up to request clarification or add additional context in comments.

1 Comment

Helped alot. Please also see the full answer posted by me.
1

Thanks for your helps all my friend.

The final code that worked:

#Build subplot with three rows and two columns
nrows = 3
ncols = 2
fig, axes = plt.subplots(figsize=(12, 16) , nrows = nrows, ncols = ncols)
fig.tight_layout()

#five categorical columns and three numerical columns of interest
for i, category in enumerate(['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5']):   
    ax = axes[i%nrows][i%ncols]
    data.groupby(category).sum()[['Num1','Num2','Num3']].plot.bar(rot=0, ax=ax)

#Rotating xticks for all
for ax in fig.axes:
    plt.sca(ax)
    plt.xticks(rotation=90)
    fig.tight_layout()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.