|
From: Stan W. <sta...@nr...> - 2011-08-22 21:06:21
|
import numpy as np
import matplotlib.ticker as mticker
class RStripScalarFormatter(mticker.ScalarFormatter):
"""
Formats as ScalarFormatter but without trailing zeros.
The 'format' attribute of ScalarFormatter instances contains the basic
number formatting as well as the formatting for TeX or MathText. Here we
separate those into the 'format' and 'wrapformat' attributes, respectively.
"""
# Code adapted from mticker.ScalarFormatter.
def __init__(self, useOffset=True, useMathText=False):
mticker.ScalarFormatter.__init__( self, useOffset=useOffset,
useMathText=useMathText )
if self._usetex:
self.wrapformat = '$%s$'
elif self._useMathText:
self.wrapformat = '$\mathdefault{%s}$'
else:
self.wrapformat = '%s'
def _set_format(self):
# set the format string to format all the ticklabels
# The floating point black magic (adding 1e-15 and formatting
# to 8 digits) may warrant review and cleanup.
locs = ( (np.asarray(self.locs) - self.offset) /
10**self.orderOfMagnitude ) + 1e-15
maxsigfigs = max( len(str('%1.8f' % loc).split('.')[1].rstrip('0'))
for loc in locs )
self.format = '%1.' + str(maxsigfigs) + 'f'
def pprint_val(self, x):
xp = (x - self.offset) / 10**self.orderOfMagnitude
if np.absolute(xp) < 1e-8:
xp = 0
xpstr = ( (self.format % xp).rstrip('0').rstrip('.')
or '0' ) # If nothing is left, it must've been zero.
return self.wrapformat % xpstr
if __name__ == '__main__':
import matplotlib.pyplot as plt
plt.plot([-0.005, 0.02])
axes = plt.gca()
axes.yaxis.set_major_formatter(RStripScalarFormatter())
plt.show()
|