diff --git a/doc/gallery/plot_rasterio_rgb.py b/doc/gallery/plot_rasterio_rgb.py index 35c1d0448fe..ec2bbe63218 100644 --- a/doc/gallery/plot_rasterio_rgb.py +++ b/doc/gallery/plot_rasterio_rgb.py @@ -26,9 +26,6 @@ # Read the data da = xr.open_rasterio('RGB.byte.tif') -# Normalize the image -da = da / 255 - # The data is in UTM projection. We have to set it manually until # https://github.com/SciTools/cartopy/issues/813 is implemented crs = ccrs.UTM('18N') diff --git a/xarray/plot/plot.py b/xarray/plot/plot.py index d17ceb84e16..97fee5f01c0 100644 --- a/xarray/plot/plot.py +++ b/xarray/plot/plot.py @@ -710,8 +710,12 @@ def imshow(x, y, z, ax, **kwargs): # missing data transparent. We therefore add an alpha channel if # there isn't one, and set it to transparent where data is masked. if z.shape[-1] == 3: - z = np.ma.concatenate((z, np.ma.ones(z.shape[:2] + (1,))), 2) - z = z.copy() + alpha = np.ma.ones(z.shape[:2] + (1,), dtype=z.dtype) + if np.issubdtype(z.dtype, np.integer): + alpha *= 255 + z = np.ma.concatenate((z, alpha), axis=2) + else: + z = z.copy() z[np.any(z.mask, axis=-1), -1] = 0 primitive = ax.imshow(z, **defaults) diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py index 1573577a092..479b1dce9da 100644 --- a/xarray/tests/test_plot.py +++ b/xarray/tests/test_plot.py @@ -1146,6 +1146,13 @@ def test_normalize_rgb_one_arg_error(self): for kwds in [dict(vmax=-1, vmin=-1.2), dict(vmin=2, vmax=2.1)]: da.plot.imshow(**kwds) + def test_imshow_rgb_values_in_valid_range(self): + da = DataArray(np.arange(75, dtype='uint8').reshape((5, 5, 3))) + _, ax = plt.subplots() + out = da.plot.imshow(ax=ax).get_array() + assert out.dtype == np.uint8 + assert (out[..., :3] == da.values).all() # Compare without added alpha + class TestFacetGrid(PlotTestCase): def setUp(self):