Force use of scientific style for basemap colorbar labels
Asked Answered
B

1

6

String formatting can by used to specify scientific notation for matplotlib.basemap colorbar labels:

cb = m.colorbar(cs, ax=ax1, format='%.4e')

But then each label is scientifically notated with the base.

If numbers are large enough, the colobar automatically reduces them to scientific notation, placing the base (i.e. x10^n) at the top of the color bar, leaving only the coefficient numbers as labels.

You can do this with a standard axis with the following:

ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0))

Is there an equivalent method for matplotlib.basemap colorbars, or perhaps a standard matplotlib colorbar?

Bassorilievo answered 18/8, 2014 at 11:48 Comment(0)
M
14

There's no one-line method, but you can do this by updating the colorbar's formatter and then calling colorbar.update_ticks().

import numpy as np
import matplotlib.pyplot as plt

z = np.random.random((10,10))

fig, ax = plt.subplots()
im = ax.imshow(z)
cb = fig.colorbar(im)

cb.formatter.set_powerlimits((0, 0))
cb.update_ticks()

plt.show()

enter image description here

The reason for the slightly odd way of doing things is that a colorbar actually has statically assigned ticks and ticklabels. The colorbar's axes (colorbar.ax) actually always ranges between 0 and 1. (Therefore, altering colorbar.ax.yaxis.formatter doesn't do anything useful.) The tick positions and labels are calculated from colorbar.locator and colorbar.formatter and are assigned when the colorbar is created. Therefore, if you need precise control over a colorbar's ticks/ticklables, you need to explicitly call colorbar.update_ticks() after customizing how the ticks are displayed. The colorbar's convenience functions do this for you behind the scenes, but as far as I know, what you want can't be done through another method.

Mistrial answered 18/8, 2014 at 19:7 Comment(2)
Excellent. That would have certainly taken me far too long to figure out. So I presume this would also work for a basemap colorbar? Thanks Joe.Bassorilievo
Happy to help! It should work exactly the same for a basemap colorbar. I don't think basemap axes change the colorbar in any way, but I could be wrong about that.Mistrial

© 2022 - 2024 — McMap. All rights reserved.