1

I made some maps as a vector file over several raster, arranged in facets. I used rasterio, matplotlib and geopandas. How to plot also the colorbar at the right of each facet?

import rasterio as rio
import geopandas as gpd
import matplotlib.pyplot as plt

ras1 = rio.open("/path/file1.tif")
ras2 = rio.open("/path/file2.tif")
vecGpd = gpd.read_file("/path/file3.tif")

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

plot1 = rio.plot.show(source=ras1, ax=ax[0,0])
vecGpd.plot(ax=plot1)
# add here colorbar 1

plot2 = rst.plot.show(source=ras2, ax=ax[0,1])
vecGpd.plot(ax=plot2)
# add here colorbar 2
            
plt.show()

1 Answer 1

2
import numpy as np

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()
b2 = rasterio.open()
b3 = rasterio.open()

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

bres1 = np.reshape(ba1, (ba1.shape[0]*ba1.shape[1], ba1.shape[2]))
bres2 = np.reshape(ba2, (ba2.shape[0]*ba2.shape[1], ba2.shape[2]))
bres3 = np.reshape(ba3, (ba3.shape[0]*ba3.shape[1], ba3.shape[2]))


# Read geometry

shapefile = gpd.read_file()


# Plot raster colorbar

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

base1 = plt.imshow(bres1)
base2 = plt.imshow(bres2)
base3 = plt.imshow(bres3)

image1  = rasterio.plot.show(b1, ax=ax[0,0], cmap='nipy_spectral', title='Band 1')
image2  = rasterio.plot.show(b2, ax=ax[0,1], cmap='nipy_spectral', title='Band 2')
image3  = rasterio.plot.show(b3, ax=ax[1,0], cmap='nipy_spectral', title='Band 3')

shapefile.plot(ax=image1, color='red')
shapefile.plot(ax=image2, color='red')
shapefile.plot(ax=image3, color='red')

fig.colorbar(base1, ax=ax[0,0])
fig.colorbar(base2, ax=ax[0,1])
fig.colorbar(base3, ax=ax[1,0])

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

enter image description here

3
  • Thank you very much again Salim. It works
    – ilFonta
    Commented Feb 20, 2022 at 15:25
  • Just another question: how to delete the labels of the axis? Thanx
    – ilFonta
    Commented Feb 21, 2022 at 16:30
  • Public another post
    – Helios
    Commented Feb 21, 2022 at 18:00

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.