'Scientific tick label notation tuning

I am not completely satisfied with the default scientific formatting for the tick labels. For example,

import numpy as np
import pylab

pylab.rcParams['text.usetex'] = True
pylab.ticklabel_format(style='sci')

pylab.figure(1)
pylab.clf()
pylab.scatter(range(10),np.linspace(-21.305,-21.300,10))
pylab.show()

gives a picture with ticklabels of the form

enter image description here

What's wrong in here is firstly that -2.1298x10^1 should be in my opinion -21.298, and in general I would only like to see only exponents divisible with 3 (10^3, 10^6 etc and in the case of 10^0 i would like to hide it as in -21.298).

Also, I would like to have instead of 0.000 and -0.002 and so on 0 and -2 so that the exponent 10^-3 is included to the -21.298 so that in total the ticklabels would be

   x 10^-3 - 21.298
 0
-2
-4
-6

Now, have I missed some easy way to do this? Thank you in advance.



Solution 1:[1]

You can achieve it using the ScalarFormatter:

from matplotlib.ticker import ScalarFormatter

sf = ScalarFormatter()
sf.set_scientific(True)
sf.set_powerlimits((-0.00001, 0.00001))

ax = pylab.gca()
ax.yaxis.set_major_formatter(sf)
pylab.show()

You can test what the formatter will do to a given number by passing the number to format_data():

sf.format_data(0.002)
#'2{\\times}10^{-3}'

Solution 2:[2]

ax.ticklabel_format(style='scientific', scilimits=(-1, 2), axis='y',useMathText=True)

set useMathText=True to turn 1e-3 to 10 \ times -3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saullo G. P. Castro
Solution 2 Willy satrio nugroho