Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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

like image 995
Reed Johnson Avatar asked May 13 '17 20:05

Reed Johnson


2 Answers

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

ax = ax.flatten()
for a in ax:
    a.imshow(img, interpolation='none')
plt.show()
like image 113
Mohamed A. Hashem Avatar answered Sep 19 '22 02:09

Mohamed A. Hashem


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')
like image 32
Arya McCarthy Avatar answered Sep 22 '22 02:09

Arya McCarthy