Created
August 8, 2017 06:12
-
-
Save Mortal/de15681e50219ba3616df5163d30fb4d to your computer and use it in GitHub Desktop.
Nicer offset in matplotlib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
from matplotlib.ticker import ScalarFormatter | |
#import seaborn as sns | |
class MyScalarFormatter(ScalarFormatter): | |
def get_offset(self): | |
a = self.get_scale_string() | |
b = self.get_offset_string() | |
if a or b: | |
return '$%s$' % self.fix_minus(a + b) | |
return '' | |
def get_scale_string(self): | |
if self.orderOfMagnitude: | |
return r'\times 10^{%.0f}' % self.orderOfMagnitude | |
else: | |
return '' | |
def get_offset_string(self): | |
if self.offset: | |
s = '%+g' % self.offset | |
if 'e' in s: | |
b, e = s.split('e') | |
return r'%s \times 10^{%s}' % (b, e.lstrip('+0')) | |
else: | |
return s | |
else: | |
return '' | |
def main(): | |
e = -8 | |
o = 1.234 | |
data = [ | |
(0, 0), | |
(-8, 0), | |
(8, 0), | |
(0, 1.25e8), | |
(-8, 1.25), | |
(8, 1.25e16), | |
] | |
for i, (e, o) in enumerate(data): | |
x = [o + 2*10**e, o + 3*10**e] | |
y = [1, 1] | |
plt.plot(x, y) | |
plt.gca().get_xaxis().set_major_formatter(MyScalarFormatter()) | |
plt.savefig('test%s.png' % i) | |
plt.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment