Reputation: 7782
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")
How can I fill up the other subplots?
Upvotes: 1
Views: 3413
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()
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()
And finally, you could put all boxplots together just by:
df2.plot(kind='box', figsize=(8,8))
plt.show()
For more info about how to make visualization with pandas check out the documentation.
Upvotes: 6
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