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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With