1

I need to plot four arrays arranged in subplots using Python and matplotlib. I prefer grey scale colormap. How to plot the NaN values that can be present in each array in red?

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import gdal

raster1 = gdal.Open("/path/file1.tif")   
array1 = np.array(raster1.GetRasterBand(1).ReadAsArray()) 
plt.subplot(2, 2, 1)
plt.imshow(array1, 
           vmin=0, vmax=1, 
           cmap=cm.get_cmap("Greys_r"))

raster2 = gdal.Open("/path/file2.tif")   
array1 = np.array(raster2.GetRasterBand(1).ReadAsArray()) 
plt.subplot(2, 2, 2)
plt.imshow(array2, 
           vmin=0, vmax=1, 
           cmap=cm.get_cmap("Greys_r"))

raster3 = gdal.Open("/path/file3.tif")   
array3 = np.array(raster3.GetRasterBand(1).ReadAsArray()) 
plt.subplot(2, 2, 3)
plt.imshow(array3, 
           vmin=0, vmax=1, 
           cmap=cm.get_cmap("Greys_r"))

raster4 = gdal.Open("/path/file4.tif")   
array4 = np.array(raster4.GetRasterBand(1).ReadAsArray()) 
plt.subplot(2, 2, 4)
plt.imshow(array4, 
           vmin=0, vmax=1, 
           cmap=cm.get_cmap("Greys_r"))
2
  • Where is the geospatial component of your question ?
    – gene
    Mar 12 at 14:23
  • Hi Gene, I tried to add the geospatial info you asked me
    – ilFonta
    Mar 12 at 14:43

1 Answer 1

0

Look this code:

import numpy as np
from osgeo import gdal
import matplotlib.pyplot as plt

# Open raster
raster = gdal.Open(inputpath_raster)

# Open like band
band = raster.GetRasterBand(1)

# Read numpy array
array = band.ReadAsArray()

# Creat a mask
masked_array = np.ma.array (array, mask=np.isnan(array))

# Make a copy
cmap = plt.cm.get_cmap("Greys_r").copy()

# Choose the color
cmap.set_bad('red',1.)

# Plot
plt.imshow(masked_array, interpolation='nearest', cmap=cmap)
plt.show()

enter image description here

The same process for each raster

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.