glue-viz / glue

Linked Data Visualizations Across Multiple Files
http://glueviz.org
Other
721 stars 152 forks source link

Render nans as 'bad' in mpl cmaps when mode='colormap' #2427

Closed bmorris3 closed 11 months ago

bmorris3 commented 11 months ago

Description

By default, image viewers cast NaNs to zero before applying a colormap. This prevents the use of the matplotlib "bad" feature. For each colormap, values above or below the colormap vmin/vmax are rendered with an optionally specified value, and "bad" values (usually nans) are rendered by a third value:

import matplotlib.pyplot as plt

plt.cm.viridis
Screen Shot 2023-08-07 at 12 39 22

By default, bad is color='k', alpha=0, but this can be changed with:

plt.cm.viridis.set_bad(color='r')

which allows users to clearly visualize nans efficiently and without special handling.

Glue currently forces nans to zero before they are converted to colors by the colormap: https://github.com/glue-viz/glue/blob/0f83a03c997b78476043485f4145f6e69cb8a8cf/glue/viewers/image/composite_array.py#L140 which prevents the user from ever making use of the bad functionality.

This PR allows the user to set a private attribute on the CompositeArray class called _set_nans_to_zero. When True, the behavior is unchanged. When set to False by a user, nans are not forced to zero, and the bad values are rendered as described by the mpl colormap. An example is shown below using Imviz from jdaviz:

Screen Shot 2023-08-07 at 12 43 43
bmorris3 commented 11 months ago

As of e01db76, nans are forced to zero when mode='color', and no zeros are forced when mode='colormap'.

astrofrog commented 11 months ago

It looks like some tests will need to be updated

bmorris3 commented 11 months ago

@astrofrog All fixed!