0

I tried to plot the subplots using the below code .But I am getting 'AttributeError: 'numpy.ndarray' object has no attribute 'boxplot'.

but changing the plt.subplots(1,2) it is plotting the box plot with indexerror.

import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.Figure(figsize=(10,5))

x = [i for i in range(100)]


fig , axes = plt.subplots(2,2)

for i in range(4):
    sns.boxplot(x, ax=axes[i])

plt.show();

I am expecting four subplots should be plotted but AttributeError is throwing

1 Answer 1

0

Couple of issues in your plot:

  • You are defining the figure twice which is not needed. I merged them into one.
  • You were looping 4 times using range(4) and using axes[i] for accessing the subplots. This is wrong for the following reason: Your axes is 2 dimensional so you need 2 indices to access it. Each dimension has length 2 because you have 2 rows and 2 columns so the only indices you can use are 0 and 1 along each axis. For ex. axes[0,1], axes[1,0] etc.
  • As @DavidG pointed out, you don't need the list comprehension. YOu can directly use range(100)

The solution is to expand/flatten make your 2d axes object and then directly iterate over it which gives you individual subplot, one at a time. The order of subplots will be row wise.


Complete working code

import matplotlib.pyplot as plt
import seaborn as sns

x = range(100)

fig , axes = plt.subplots(2,2, figsize=(10,5))

for ax_ in axes.flatten():
    sns.boxplot(x, ax=ax_)

plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Could even remove the list comprehension as that isn't really needed either?

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.