Matplotlib: TypeError: 'AxesSubplot' object is not subscriptable

SHV_la picture SHV_la · Sep 11, 2018 · Viewed 38.1k times · Source

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?

Answer

SpghttCd picture SpghttCd · Sep 11, 2018
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.