Matplotlib: TypeError: 'AxesSubplot' object is not subscriptable

Question:

I am trying to make a simple box plot of a variable ‘x’ contained in two dataframes, df1 and df2. To do this I am using the following code:

fig, axs = plt.subplots()
axs[0, 0].boxplot([df1['x'], df2['x']])
plt.show();

However, I get this:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-108-ce962754d553> in <module>()
----> 2 axs[0, 0].boxplot([df1['x'], df2['x']])
      3 plt.show();
      4 

TypeError: 'AxesSubplot' object is not subscriptable

Any ideas?

Asked By: SHV_la

||

Answers:

fig, axs = plt.subplots()

returns a figure with only one single subplot, so axs already holds it without indexing.

fig, axs = plt.subplots(3)

returns a 1D array of subplots.

fig, axs = plt.subplots(3, 2)

returns a 2D array of subplots.

Note that this is only due to the default setting of the kwarg squeeze=True.
By setting it to False you can force the result to be a 2D-array, independant of the number or arrangement of the subplots.

Answered By: SpghttCd
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.