Matplotlib colorbar ticks format when using scientific notation

4.2k views Asked by At

I'm bothering you with a silly question, but I couldn't find an awnser. I'm trying to add a colorbar to an image using matplotlib. The issue comes when I try to format the ticks of the colorbar. I would like to have a scientific notation format, but at the same time control the number of decimals in the ticks. For example, with this code:

#format the colorbar ticks labels
sfmt=ticker.ScalarFormatter(useMathText=True) 
sfmt.set_powerlimits((0, 0))

cb1=fig1.colorbar(imp,
              cax=axcbar,
              orientation="vertical",
              ticks=np.linspace(1.03*np.min(imest),0.97*np.max(imest),4),
              format=sfmt)
cb1.set_label(r'$kg/s.m^2$')

I create this figure:

enter image description here

I would like to have in the ticks only one decimal (i.e. 5.210 --> 5.2). Is this possible in a simple way? I've tried a lot of things without success.

Thanks in advance.

1

There are 1 answers

0
Lucas On BEST ANSWER

You can change the tick's array from

ticks = np.linspace(1.03*np.min(imest),0.97*np.max(imest),4)

to something like:

ticks = np.arange(2.2, 6.2, 1) * 1e6

And the result would look like the plot: enter image description here