Align ticklabels in matplotlib colorbar

I was just about to ask the same question, then finally found yours. So I'd like to add my own work-around.

At first I used the exact same solution given by Rutger Kassies. However, when plotting in ipython, the same amount of shift in x position will give wildly different results when viewing a small window, or setting the figure to full screen.

I've eventually settled on setting the pad of the colorbar's tick labels. Borrowing Blatantly stealing the sample code of Rutger:

a = np.random.randn(10,10)

fig, ax = plt.subplots()

im = ax.imshow(a, interpolation='none')
cb = plt.colorbar(im)

ticklabs = cb.ax.get_yticklabels()
cb.ax.set_yticklabels(ticklabs,ha='right')
cb.ax.yaxis.set_tick_params(pad=45)  # your number may vary

This workaround seems to give a much more consistent result when using across various window sizes and aspects.

Here's 4 outputs to demonstrate what I mean: top row is the position shifting solution, bottom row is my padding solution. On the left are the default figure window sizes, the right side was savefigged after popping the figure window to full screen:

top row older solution, bottom row is mine


You can change the alignment of the text. It might be necessary to change the (x) position of the label a bit to prevent overlap with the colorbar itself.

a = np.random.randn(10,10)

fig, ax = plt.subplots()

im = ax.imshow(a, interpolation='none')
cb = plt.colorbar(im)

for t in cb.ax.get_yticklabels():
    t.set_horizontalalignment('right')   
    t.set_x(3.5)

enter image description here