Skip to content

[Bug]: imshow allows RGB(A) images with np.nan values to pass #27301

Closed
@shaperilio

Description

@shaperilio

Bug summary

Using imshow to visualize a 2x2x1 array with nans scattered throughout works as expected. With the default "bad" color of black with alpha = 0, you'll see an axis' facecolor where the nans are.

With a 2x2x3 array, the nans are always black.

With a 2x2x4 array, and the alpha manually set to 0 where the nans are, you get the correct behavior (i.e. you can see the axis where the nans are).

Code for reproduction

import numpy
from matplotlib import pyplot

img = numpy.ones((2, 2))  # single channel 2x2
img_nan = img.copy()
img_nan[0, 0] = float('nan')

img3 = numpy.ones((2, 2, 3))  # RGB 2x2
img3_nan = img3.copy()
img3_nan[0, 0, :] = float('nan')

img4 = numpy.ones((2, 2, 4))  # RGBA 2x2
img4_nan = img4.copy()
img4_nan[0, 0, :] = float('nan')
img4_nan[0, 0, 3] = 0  # alpha


def imshow(a):
    pyplot.figure()
    im = pyplot.imshow(a)
    # im.get_cmap().set_bad(color='y', alpha=1) # only works for single channel images
    im.get_cmap().set_bad(alpha=0)
    pyplot.gca().set_facecolor('y')


imshow(img_nan)   # nan shows up as 'y'
imshow(img3_nan)  # nan shows up as black
imshow(img4_nan)  # nan shows up as 'y'


pyplot.show()

Actual outcome

image
image
image

Expected outcome

Figures 2 and 3 above should look identical.

Additional information

I traced through imshow and cannot see any difference between the single- and 3-channel image; the mask is there and it's correct in both cases. So I wonder if this is a backend issue?

Operating system

Windows

Matplotlib Version

3.7.3

Matplotlib Backend

QtAgg

Python version

3.8.10

Jupyter version

No response

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions