It seems pcolormesh have a different way of handling colorbar tick position and label than other Python tools. I can't get my labels at the desired position : centered by color segment (see image: current rendering where the ticks are misaligned).
# Add a colorbar with commune names
cbar = plt.colorbar(mesh, ax=ax, ticks=np.arange(1, len(commune_names) + 1))
# Set the tick labels to the commune names
cbar.set_ticklabels(commune_names)
I tested many things, also using AI, but couldn't figure it out.
# Add a colorbar with commune names
cbar = plt.colorbar(mesh, ax=ax)
# Set up tick labels and positions
k = len(commune_names)
labels = np.arange(1, k + 1) # Commune IDs, from 1 to k
loc = labels - 0.5 # Shift ticks by 0.5 to center them in the color segments
# Set the ticks and labels
cbar.set_ticks(loc)
cbar.set_ticklabels(commune_names)
# Adjust the tick size (optional)
cbar.ax.tick_params(labelsize=10)
Thanks for your help.
I did find a solution using a dummy case (and AI) Please see below for an example with five points (grid cells) to be plotted with pcolormesh. I missed the following:
from matplotlib.colors import ListedColormap, BoundaryNorm
...
bounds = np.arange(0.5, 6.5, 1) # Boundaries between colors
norm = BoundaryNorm(bounds, cmap.N)
...
c = ax.pcolormesh(lon, lat, data, cmap=cmap, norm=norm, shading='auto')
It is necessary to define the bounds and norm.