I am plotting data onto a PlateCarree or Mercator projection with a colorbar at the side. If I use the mercator projection, than the colorbar is nicely aligned with the height of the figure, but if I use the plate carree projection than the colorbar is not aligned with the height of the figure. How could I automate this that is independent of the map projection?
Here is my code:
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.set_extent([6, 44, 55, 72], crs=ccrs.PlateCarree())
ax.coastlines(linewidth=.5)
ax.add_feature(cfeature.LAND, color='white', alpha=.15)
ax.add_feature(cfeature.BORDERS, linestyle='-', linewidth=.6)
# data
dataset = rasterio.open(fpath)
dbz = dataset.read()
# Plotting geoTIFF-Data
extent = (dataset.bounds.left, dataset.bounds.right, dataset.bounds.bottom, dataset.bounds.top)
boundaries = [-10,-5,0,5,7.5,10,12.5,15,20,25,30,35,40,45,50]
colors = ('#FF000000', '#c4c4e4','#8989c9','#4e4eaf','#141494','#272776','#626256','#9d9d35','#d8d815','#f6eb00','#dbb100','#c17600','#a63b00','#8b0000')
cmap = mcolors.ListedColormap(colors)
norm = mcolors.BoundaryNorm(boundaries, cmap.N)
im = ax.imshow(dbz_reshaped, extent=extent, cmap=cmap, norm=norm, transform=ccrs.epsg(9391))
fig.colorbar(im, ax=ax, orientation='vertical', label='DBZ')
The different figures look like:
>Solution :
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import rasterio
# Load your data
dataset = rasterio.open(fpath)
dbz = dataset.read()
# Create the figure and axis
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
# Set the extent and plot features
ax.set_extent([6, 44, 55, 72], crs=ccrs.PlateCarree())
ax.coastlines(linewidth=.5)
ax.add_feature(cfeature.LAND, color='white', alpha=.15)
ax.add_feature(cfeature.BORDERS, linestyle='-', linewidth=.6)
# Plot the data
extent = (dataset.bounds.left, dataset.bounds.right, dataset.bounds.bottom, dataset.bounds.top)
boundaries = [-10,-5,0,5,7.5,10,12.5,15,20,25,30,35,40,45,50]
colors = ('#FF000000', '#c4c4e4','#8989c9','#4e4eaf','#141494','#272776','#626256','#9d9d35','#d8d815','#f6eb00','#dbb100','#c17600','#a63b00','#8b0000')
cmap = mcolors.ListedColormap(colors)
norm = mcolors.BoundaryNorm(boundaries, cmap.N)
im = ax.imshow(dbz_reshaped, extent=extent, cmap=cmap, norm=norm, transform=ccrs.epsg(9391))
# Adjust colorbar size relative to figure height
divider = make_axes_locatable(ax)
cax = divider.new_horizontal(size="5%", pad=0.05, axes_class=plt.Axes)
fig.add_axes(cax)
cbar = fig.colorbar(im, cax=cax, orientation='vertical', label='DBZ')
plt.show()

