Search code examples
pythonmatplotlibcolorbar

Offset tick labels in colorbar


Consider the following image (the code to generate it is below):

enter image description here

The upper tick label (9.5E-05) looks ok, but I want the bottom and middle tick label to be aligned upwards vertically (notice that it is not the same alignment applied to both) so that they look like this:

enter image description here

which looks much better (to me at least). I've been looking around but have not found a way to do this.


import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable


ax = plt.subplot(111)
data = np.random.uniform(0., 10., (50, 50))
im = plt.imshow(data)

# Colorbar on the right side of ax.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="2%", pad=0.05)
cbar = plt.colorbar(im, cax=cax)
cbar.set_ticks([np.min(data), np.ptp(data) * .5, np.max(data)])
print(np.min(data), np.ptp(data) * .5, np.max(data))

cbar.ax.set_yticklabels([
    '{:.1E}'.format(0.00000133),
    '{:.1E}'.format(0.00000561),
    '{:.1E}'.format(0.0000948)], rotation=90)

plt.show()

Solution

  • You can loop through the colorbar's y tick labels and set the vertical alignment of the text depending on which label it is.

    # don't include last label (one at the top) as we don't want to change its alignment
    for i, label in enumerate(cbar.ax.get_yticklabels()[:-1]):
        if i == 0:  # first label
            label.set_va("bottom")
        else:
            label.set_va("center")
    

    enter image description here