Search code examples
pythonaxesindex-error

python axes.ravel() IndexError: too many indices for array


I am trying to plot 2*2 images. with the code below.

fig, axes = plt.subplots(nrows=2, ncols=2)
ax = axes.ravel()
ax[0, 0].imshow(im1px, cmap='gray')
ax[0, 1].imshow(im2px, cmap='gray')
ax[1, 0].imshow(im3px, cmap='gray')
ax[1, 1].imshow(im3px, cmap='gray')

And it throws error messages like this '''

    IndexError                                Traceback (most recent call last)
    in 
      1 fig, axes = plt.subplots(nrows=2, ncols=2)
      2 ax = axes.ravel()
----> 3 ax[0, 0].imshow(im1px, cmap='gray')
      4 ax[0, 1].imshow(im2px, cmap='gray')
      5 ax[1, 0].imshow(im3px, cmap='gray')

    IndexError: too many indices for array

''' Please help to tell how to resolve it


Solution

  • Why are you using ravel ?

    You are getting the error because ravel flattens the 2x2, and then you are using a 2d index.

    >>> fig, axes = plt.subplots(nrows=2, ncols=2)
    >>> axes.shape
    (2, 2)
    >>> axes.ravel().shape
    (4,)
    

    Instead just use

    axes[0,0], axes[0,1]... etc.