Matplotlib: TypeError: ‘AxesSubplot’ object is not subscriptable [duplicate]

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, independent of the number or arrangement of the subplots.

import numpy
from PIL import Image
import matplotlib.pyplot as plt

imarray = numpy.random.rand(10,10,3) * 255
im = Image.fromarray(imarray.astype('uint8')).convert('RGBA')

#rows = 1; cols = 1;
#rows = 5; cols = 3;
rows = 1; cols = 5;
fig, ax = plt.subplots(rows, cols, squeeze=False)
fig.suptitle('random plots')
i = 0
for r in range(rows):
    for c in range(cols): 
        ax[r][c].imshow(im)
        i = i + 1     
plt.show()
plt.close()

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)