Skip to content

Commit 6decf96

Browse files
committed
Add AutoFormatter features to SimpleFormatter & others
1 parent c763629 commit 6decf96

File tree

1 file changed

+66
-32
lines changed

1 file changed

+66
-32
lines changed

proplot/ticker.py

Lines changed: 66 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import locale
1010
from fractions import Fraction
1111
from .internals import ic # noqa: F401
12-
from .internals import _not_none
12+
from .internals import docstring, _not_none
1313

1414
__all__ = [
1515
'AutoFormatter',
@@ -23,6 +23,20 @@
2323
REGEX_MINUS_ZERO = re.compile('\\A[-\N{MINUS SIGN}]0(.0*)?\\Z')
2424

2525

26+
docstring.snippets['formatter.params'] = """
27+
zerotrim : bool, optional
28+
Whether to trim trailing zeros. Default is :rc:`axes.formatter.zerotrim`.
29+
tickrange : (float, float), optional
30+
Range within which major tick marks are labelled. Default is ``(-np.inf, np.inf)``.
31+
prefix, suffix : str, optional
32+
Prefix and suffix for all strings.
33+
negpos : str, optional
34+
Length-2 string indicating the suffix for "negative" and "positive"
35+
numbers, meant to replace the minus sign. This is useful for indicating
36+
cardinal geographic coordinates.
37+
"""
38+
39+
2640
class AutoFormatter(mticker.ScalarFormatter):
2741
"""
2842
The new default formatter. Differs from `~matplotlib.ticker.ScalarFormatter`
@@ -33,25 +47,17 @@ class AutoFormatter(mticker.ScalarFormatter):
3347
3. Permits adding arbitrary prefix or suffix to every tick label string.
3448
4. Permits adding "negative" and "positive" indicator.
3549
"""
50+
@docstring.add_snippets
3651
def __init__(
3752
self,
3853
zerotrim=None, tickrange=None,
39-
prefix=None, suffix=None, negpos=None, **kwargs
54+
prefix=None, suffix=None, negpos=None,
55+
**kwargs
4056
):
4157
"""
4258
Parameters
4359
----------
44-
zerotrim : bool, optional
45-
Whether to trim trailing zeros.
46-
Default is :rc:`axes.formatter.zerotrim`.
47-
tickrange : (float, float), optional
48-
Range within which major tick marks are labelled.
49-
prefix, suffix : str, optional
50-
Prefix and suffix for all strings.
51-
negpos : str, optional
52-
Length-2 string indicating the suffix for "negative" and "positive"
53-
numbers, meant to replace the minus sign. This is useful for
54-
indicating cardinal geographic coordinates.
60+
%(formatter.params)s
5561
5662
Other parameters
5763
----------------
@@ -219,7 +225,7 @@ def _trim_trailing_zeros(string, use_locale=None):
219225
return string
220226

221227

222-
def SigFigFormatter(sigfig=1, zerotrim=False):
228+
def SigFigFormatter(sigfig=1, zerotrim=None):
223229
"""
224230
Return a `~matplotlib.ticker.FuncFormatter` that rounds numbers
225231
to the specified number of *significant digits*.
@@ -231,24 +237,34 @@ def SigFigFormatter(sigfig=1, zerotrim=False):
231237
zerotrim : bool, optional
232238
Whether to trim trailing zeros.
233239
"""
234-
def fmt(x, pos):
240+
from .config import rc
241+
zerotrim = _not_none(zerotrim, rc['axes.formatter.zerotrim'])
242+
243+
def func(x, pos):
244+
# Limit digits to significant figures
235245
if x == 0:
236246
digits = 0
237247
else:
238248
digits = -int(np.log10(abs(x)) // 1)
239249
digits += sigfig - 1
240250
x = np.round(x, digits)
241251
string = ('{:.%df}' % max(0, digits)).format(x)
242-
if zerotrim and '.' in string:
243-
string = string.rstrip('0').rstrip('.')
244-
string = string.replace('-', '\N{MINUS SIGN}')
245-
if string == '\N{MINUS SIGN}0':
246-
string = '0'
252+
string = string.replace('.', AutoFormatter._get_decimal_point())
253+
254+
# Custom string formatting
255+
string = AutoFormatter._minus_format(string)
256+
if zerotrim:
257+
string = AutoFormatter._trim_trailing_zeros(string)
247258
return string
248-
return mticker.FuncFormatter(fmt)
249259

260+
return mticker.FuncFormatter(func)
250261

251-
def SimpleFormatter(precision=6, zerotrim=True):
262+
263+
@docstring.add_snippets
264+
def SimpleFormatter(
265+
precision=6, zerotrim=None, tickrange=None,
266+
prefix=None, suffix=None, negpos=None, **kwargs
267+
):
252268
"""
253269
Return a `~matplotlib.ticker.FuncFormatter` that replicates the
254270
`zerotrim` feature from `AutoFormatter`. This is more suitable for
@@ -258,22 +274,38 @@ def SimpleFormatter(precision=6, zerotrim=True):
258274
Parameters
259275
----------
260276
precision : int, optional
261-
The maximum number of digits after the decimal point.
262-
zerotrim : bool, optional
263-
Whether to trim trailing zeros.
264-
Default is :rc:`axes.formatter.zerotrim`.
277+
The maximum number of digits after the decimal point. Default is ``6``.
278+
%(formatter.params)s
265279
"""
266280
from .config import rc
267281
zerotrim = _not_none(zerotrim, rc['axes.formatter.zerotrim'])
282+
tickrange = tickrange or (-np.inf, np.inf)
283+
prefix = prefix or ''
284+
suffix = suffix or ''
285+
negpos = negpos or ''
268286

269287
def func(x, pos):
288+
# Tick range limitation
289+
if AutoFormatter._outside_tick_range(x, tickrange):
290+
return ''
291+
292+
# Negative positive handling
293+
x, tail = AutoFormatter._neg_pos_format(x, negpos)
294+
295+
# Default string formatting
270296
string = ('{:.%df}' % precision).format(x)
271-
if zerotrim and '.' in string:
272-
string = string.rstrip('0').rstrip('.')
273-
string = string.replace('-', '\N{MINUS SIGN}')
274-
if string == '\N{MINUS SIGN}0':
275-
string = '0'
297+
string = string.replace('.', AutoFormatter._get_decimal_point())
298+
299+
# Custom string formatting
300+
string = AutoFormatter._minus_format(string)
301+
if zerotrim:
302+
string = AutoFormatter._trim_trailing_zeros(string)
303+
304+
# Prefix and suffix
305+
string = AutoFormatter._add_prefix_suffix(string, prefix, suffix)
306+
string = string + tail # add negative-positive indicator
276307
return string
308+
277309
return mticker.FuncFormatter(func)
278310

279311

@@ -309,5 +341,7 @@ def func(x, pos): # must accept location argument
309341
string = f'-{symbol:s}/{frac.denominator:d}'
310342
else: # and again make sure we use unicode minus!
311343
string = f'{frac.numerator:d}{symbol:s}/{frac.denominator:d}'
312-
return string.replace('-', '\N{MINUS SIGN}')
344+
string = AutoFormatter._minus_format(string)
345+
return string
346+
313347
return mticker.FuncFormatter(func)

0 commit comments

Comments
 (0)