Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align ticklabels in matplotlib colorbar

I have a colorbar with positive and negative values which are generated automatically (I am not setting them). Unfortunately the minus sign breaks the vertical alignment of the text. How can I align all the text in the ticklabels to the right or alternatively insert a space before my positive numbers to make it look good?

enter image description here

like image 925
elyase Avatar asked Oct 07 '13 08:10

elyase


1 Answers

It's easiest to do this with the format option when creating your colorbar.

import numpy as np
import matplotlib.pyplot as plt

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

fig, ax = plt.subplots()

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

colorbar_format = '% 1.1f'
cb = plt.colorbar(im, format=colorbar_format)

So basically you use the Python "%" string format. https://pyformat.info/

If you know you have negatives note the extra space after % which will 'placehold' it for you, adding a space to positives and nothing to the negatives. You might need to play around with this to get it to fit your use case best. I've also noticed that if you aren't setting your own tick values:

cb = plt.colorbar(im, ticks=your_own_ticks, format=colorbar_format)

The number and distribution of ticks may change based on the format you use.

Example of formatted strings in plot colorbar labels

like image 127
Kenneth D Avatar answered Sep 27 '22 03:09

Kenneth D