elksie5000
elksie5000

Reputation: 7782

For to configure matplotlib subplots within a for loop

I'm trying to loop through some data in a Pandas dataframe and plot into different subplots, but not quite sure what I've got wrong.

Here's the code:

df2 = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
fig, axes = plt.subplots(nrows=4, ncols=1, sharex=True)
for i, col in enumerate(df2.columns):
    print(col)
    axes[i] = df2[col].plot(kind="box")

enter image description here

How can I fill up the other subplots?

Upvotes: 1

Views: 3413

Answers (2)

Mabel Villalba
Mabel Villalba

Reputation: 2598

There is an easier way to do this, you just need to do df.plot with the option subplots=True and then change there the outlier, vertical (layout=(4,1)):

df2.plot(kind='box',subplots=True, layout=(4,1), figsize=(8,8))
plt.show()

enter image description here

Or if you prefer the subplots to be distributed horizontally (layout=(1,4)):

df2.plot(kind='box',subplots=True, layout=(1,4),figsize=(15,8))
plt.show()

enter image description here

And finally, you could put all boxplots together just by:

df2.plot(kind='box', figsize=(8,8))
plt.show()

enter image description here

For more info about how to make visualization with pandas check out the documentation.

Upvotes: 6

Soerendip
Soerendip

Reputation: 9184

You need to pass the axis as argument to the plot function. Something along these lines:

df2 = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
fig, axes = plt.subplots(nrows=4, ncols=1, sharex=True)
for i, col in enumerate(df2.columns):
    print(col)
    df2[col].plot(kind="box", ax=axes[i])

In your example, you are redefining the elements of ´axes´. Instead, you define axes once and then you tell the plot function which axis to use for the plot.

Upvotes: 4

Related Questions