简体   繁体   中英

'numpy.ndarray' object has no attribute 'imshow'

I've been trying everything I can to get pyplot to display an image 5 times. I keep getting this error...

Here is my code

import matplotlib.pyplot as plt
import os.path
import numpy as np

'''Read the image data'''
# Get the directory of this python script
directory = os.path.dirname(os.path.abspath(__file__))
# Build an absolute filename from directory + filename
filename = os.path.join(directory, 'cat.gif')
# Read the image data into an array
img = plt.imread(filename)

'''Show the image data'''
# Create figure with 1 subplot
fig, ax = plt.subplots(1, 5)
# Show the image data in a subplot

for i in ax:
    ax.imshow(img, interpolation='none')
# Show the figure on the screen
fig.show()

I'm sure it has something to do with the 2D array, but I really cant figure it out.

Ive tried

for i in ax:
    ax[i].imshow(img, interpolation='none')
# Show the figure on the screen
fig.show()

But I just get:

IndexError: only integers, slices ( : ), ellipsis ( ... ), numpy.newaxis ( None ) and integer or boolean arrays are valid indices

This:

for i in ax:
    ax[i].imshow(img, interpolation='none')

doesn't make sense because I isn't the index. It's one of the axis objects.

And your first case is wrong because even though you loop over the items, you call the function on ax , not the individual axes.

Do this:

for a in ax:
    a.imshow(img, interpolation='none')

you can check ax like below

type(ax)
>>> <class 'numpy.ndarray'>

ax
>>> [<matplotlib.axes._subplots.AxesSubplot object at 0x0000028F13AFC668>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000028F15C6FCF8>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000028F15CA23C8>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000028F15CC9A58>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000028F15CFA160>]

if you really want to use 'i' then use enumerate() like this

for i, ax in enumerate(axs):
    ax.imshow(img[i:i*100], interpolation='none')

'axs' is preferred because it is multiple.

finally, you can test below

import numpy as np
import matplotlib.pyplot as plt
from skimage import data

'''Read the image data'''
img = data.chelsea()   # cat image

'''Show the image data'''
# Create figure with 1 subplot
fig, axs = plt.subplots(nrows=1, ncols=5, figsize=(10, 3))

print(axs)
# [<matplotlib.axes._subplots.AxesSubplot object at 0x000001D7A841C710>
#  <matplotlib.axes._subplots.AxesSubplot object at 0x000001D7AA58FCC0>
#  <matplotlib.axes._subplots.AxesSubplot object at 0x000001D7AA5C2390>
#  <matplotlib.axes._subplots.AxesSubplot object at 0x000001D7AA5E9A20>
#  <matplotlib.axes._subplots.AxesSubplot object at 0x000001D7AA61A128>]

print(axs.shape)  # (5,)

# Show the image data in a subplot
for i, ax in enumerate(axs):
    print(ax)     # AxesSubplot(0.125,0.11;0.133621x0.77)
    img_made_changeable = img[i:(i + 2) * 50]
    ax.imshow(img_made_changeable, interpolation='none')

# Show the figure on the screen
plt.show()

just add this command before " ax.flatten() " ​before your code

ax = ax.flatten()
for a in ax:
    a.imshow(img, interpolation='none')
plt.show()

Just a little addition to the previous answers:

The variable axs , on containing multiple axes, will be a 2D ndarray . For example, the subplots as 3 rows and 2 columns can be created using:

fig, axs = plt.subplots(ncols=2, nrows=3, figsize=(8, 10))

>> axs
array([[<AxesSubplot:>, <AxesSubplot:>],
       [<AxesSubplot:>, <AxesSubplot:>],
       [<AxesSubplot:>, <AxesSubplot:>]], dtype=object)

This 2D ndarray requires two indices and to make it work within a loop a single index is needed . Therefore it must be flattened first to have 1D ndarray of size (6,).

fig, axs = plt.subplots(ncols=2, nrows=3, figsize=(8, 10))
for i, ax in enumerate(axs.ravel()):
    ax.imshow(img[i])

Alternatively, one may also do like this

fig, axs = plt.subplots(ncols=2, nrows=3, figsize=(8, 10))
axes = axes.ravel()
for i in range(5):
    ax[i].imshow(img[i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM