admin管理员组

文章数量:1244304

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.

本文标签: colorbarpcolormesh color bar customed ticks positionStack Overflow