2

I'm using the function imshow from matplotlib to display several rasters using faceting. I need to overlay the vector vec.shp on each raster in each facet. I would prefere to do this with matplotlib and imshow due to the easiness of coding

import matplotlib.pyplot as plt
import gdal
import geopandas as gpd

raster1 = gdal.Open("/path/file1.tif")
raster1 = gdal.Open("/path/file2.tif")
raster1 = gdal.Open("/path/file3.tif")
# etc

vector = gpd.read_file("/path/vec.shp")

# plot 1
plt.subplot(2, 4, 1)
plt.imshow(raster1)

# plot 2 
plt.subplot(2, 4, 2)
plt.imshow(raster2)

# plot 3
plt.subplot(2, 4, 3)
plt.imshow(raster3)

# etc

I'm wondering wether is there a syntax like this

# plot 1
plt.subplot(2, 4, 1)
plt.imshow(raster1, vector)

1 Answer 1

5
# I think is better If you use rasterio, plot and matplotlib

# Look this code:   


import rasterio 
    
from rasterio import plot
    
import geopandas as gpd
    
import matplotlib.pyplot as plt

plt.rcParams['figure.figsize']=9,4

# Read raster

b1 = rasterio.open(inputpath_raster1)
b2 = rasterio.open(inputpath_raster2)
b3 = rasterio.open(inputpath_raster3)

ba1 = b1.read()
ba2 = b2.read()
ba3 = b3.read()


# Read geometry

shapefile = gpd.read_file(inputpath_shapefile)

# Plot shapefile

shapefile.plot(color='red')
plt.show()

enter image description here

# Plot raster and shapefile

fig, ax = plt.subplots(nrows=2,ncols=2, figsize=(10,10))

p1  = rasterio.plot.show(b1, ax=ax[0,0], cmap='nipy_spectral', title='Band 1')
p2  = rasterio.plot.show(b2, ax=ax[0,1], cmap='nipy_spectral', title='Band 2')
p3  = rasterio.plot.show(b3, ax=ax[1,0], cmap='nipy_spectral', title='Band 3')

shapefile.plot(ax=p1, color='red')
shapefile.plot(ax=p2, color='red')
shapefile.plot(ax=p3, color='red')

fig.delaxes(ax=ax[1,1]) 
plt.show()

enter image description here

5
  • 1
    Thank you Salim, just one correction: i think that ba1 = b1.read() is useless. All the rest is ok
    – ilFonta
    Commented Feb 17, 2022 at 11:19
  • 1
    Another question: how to add colorbar to each subplot?
    – ilFonta
    Commented Feb 17, 2022 at 11:53
  • I am going to check your question,
    – Helios
    Commented Feb 19, 2022 at 1:01
  • Do you want to create another post for your question?
    – Helios
    Commented Feb 19, 2022 at 16:09
  • I already did it. Thank you
    – ilFonta
    Commented Feb 20, 2022 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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