Python – Overlay Raster and Vector Using Matplotlib and Faceting

matplotlibpython

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)

Best Answer

# 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

Related Question