matplotlib force scientific notation and define exponent

Solutions on MaxInterview for matplotlib force scientific notation and define exponent by the best coders in the world

showing results for - "matplotlib force scientific notation and define exponent"
Anton
23 Aug 2016
1import numpy as np
2import matplotlib.pyplot as plt
3import matplotlib.ticker
4
5class OOMFormatter(matplotlib.ticker.ScalarFormatter):
6    def __init__(self, order=0, fformat="%1.1f", offset=True, mathText=True):
7        self.oom = order
8        self.fformat = fformat
9        matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,useMathText=mathText)
10    def _set_order_of_magnitude(self):
11        self.orderOfMagnitude = self.oom
12    def _set_format(self, vmin=None, vmax=None):
13        self.format = self.fformat
14        if self._useMathText:
15            self.format = r'$\mathdefault{%s}$' % self.format
16
17
18x = np.linspace(1,9,9)
19y1 = x*10**(-4)
20y2 = x*10**(-3)
21
22fig, ax = plt.subplots(2,1,sharex=True)
23
24ax[0].plot(x,y1)
25ax[1].plot(x,y2)
26
27for axe in ax:
28    axe.yaxis.set_major_formatter(OOMFormatter(-4, "%1.1f"))
29    axe.ticklabel_format(axis='y', style='sci', scilimits=(-4,-4))
30
31plt.show()
32