Search code examples
pythonpython-3.xtypeerrorimshow

zip does not work for imshow: TypeError: Image data cannot be converted to float


I saw similar questions elsewhere, but they came from different codes. My case is to transpose the data with zip, then use the imshow:

import matplotlib.pyplot as plt
a=[[1,2,3],[4,5,6]]
img_data=zip(*a)
plt.imshow(img_data)

I got TypeError: Image data cannot be converted to float


Solution

  • zip returns an iterator object (in python3, and not a container such as a list/array). What you'd want to do is convert the zip object to a format that imshow understands. There are a couple of options.

    Option 1
    Convert to a list -

    img_data = list(zip(*a))
    plt.imshow(img_data)
    

    Option 2
    Convert a to a numpy array and transpose. Since you're using zip to the same effect, this makes sense.

    plt.imshow(np.array(a).T)
    

    enter image description here