Skip to content

imshow padding around NaN values #18735

Closed
@benjimin

Description

@benjimin

There seems to be a discrepancy in how matplotlib's imshow displays rasters which contain NaN areas. The NaN areas of the raster appear larger than they really are.

I assume the problem might be that the raw raster gets resampled/interpolated during display (but before converting to RGBA) and the NaN values propagate during that interpolation (since the ordinary mean of a list containing at least one nonfinite value is also not finite). If so, a fix would be to ensure conversion to RGBA always precedes any image resampling/rescaling.

Here is an example. The first subplot shows a float32 raster with values of zero and one. The second subplot exactly replaces the nonzero pixels with NaN, however the resulting shapes look different (making narrow non-NaN features invisible). The third subplot combines both, showing that the non-NaN area (red) is eroded, resulting in a black outline.

The expected correct behaviour would be that the red layer perfectly covers the black layer, leaving no border visible.

import matplotlib.pyplot as plt, numpy as np

raster = np.full(shape=[200]*2, fill_value=np.nan, dtype=np.float32) # example image
raster[100:150, 100:150] = 0 
for i in range(10):
    raster[20*i:20*i+i, :] = 0 # lines of varying thickness
    
plt.figure(figsize=(8,8)) # small figure

plt.subplot(1,3,1).imshow(np.isnan(raster).astype(np.float32)) # 0 vs 1
plt.subplot(1,3,2).imshow(raster)                              # 0 vs NaN
 
ax = plt.subplot(1,3,3)
ax.imshow(np.isnan(raster), cmap='gray') # black border/underlayer
ax.imshow(raster, cmap='autumn')         # red interior

image

Tested on matplotlib 3.2.1, in a jupyter 1.0.0 sandbox using ipykernel.pylab.backend_inline backend, ipykernel 5.3.4, python 3.6.9, Linux 4.14 amzn2 x86_64.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions