Search code examples
pythonmatplotlibfigurecolorbar

How to set colorbar labeling text in the center of two tick marks?


I am working on a project that involves creating a colorbar for an image using Matplotlib in Python. I have managed to generate the colorbar successfully using the following code:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

im = ax.imshow([[1, 2], [3, 4]])

cbar = fig.colorbar(im, orientation='horizontal')
ticks = np.arange(1, 5)
cbar.set_ticks(ticks)
cbar.set_ticklabels(['text 1', 'text 2', 'text 3', 'text4'])

plt.show()

However, I would like to customize the colorbar so that the labeling text appears in the center of two tick marks instead of below them. Currently, the text is positioned below the tick marks. Is there a way to achieve this in Matplotlib?

Enter image description here

What I am expecting...

Enter image description here


Solution

  • You can try the following:

    cbar.set_ticklabels([])
    for tick, label in zip(cbar.get_ticks(), ['text 1', 'text 2', 'text 3', 'text 4']):
        cbar.ax.text(tick, 0.5, label, ha='center', va='center')
    

    Output: enter image description here

    EDIT:

    The edit changes and output can be achieved by calculating the midpoint between two loops. Try the following:

    cbar.set_ticklabels([])
    for i in range(len(ticks)-1):
        tick = (ticks[i] + ticks[i+1]) / 2  
        label = 'text {}'.format(i+1)
        cbar.ax.text(tick, -0.5, label, ha='center', va='top')
    

    Output: enter image description here