8000 AutoDateFormatter: More customizable formatting · matplotlib/matplotlib@ff76552 · GitHub
[go: up one dir, main page]

Skip to content

Commit ff76552

Browse files
megiespelson
authored andcommitted
AutoDateFormatter: More customizable formatting
This allows custom functions to be used for formatting in the style of FuncFormatter.
1 parent 26498aa commit ff76552

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

lib/matplotlib/dates.py

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -505,9 +505,25 @@ class AutoDateFormatter(ticker.Formatter):
505505
dictionary by doing::
506506
507507
508-
formatter = AutoDateFormatter()
509-
formatter.scaled[1/(24.*60.)] = '%M:%S' # only show min and sec
510-
508+
>>> formatter = AutoDateFormatter()
509+
>>> formatter.scaled[1/(24.*60.)] = '%M:%S' # only show min and sec
510+
511+
Custom `FunctionFormatter`s can also be used. The following example shows
512+
how to use a custom format function to strip trailing zeros from decimal
513+
seconds and adds the date to the first ticklabel::
514+
515+
>>> def my_format_function(x, pos=None):
516+
... x = matplotlib.dates.num2date(x)
517+
... if pos == 0:
518+
... fmt = '%D %H:%M:%S.%f'
519+
... else:
520+
... fmt = '%H:%M:%S.%f'
521+
... label = x.strftime(fmt)
522+
... label = label.rstrip("0")
523+
... label = label.rstrip(".")
524+
... return label
525+
>>> from matplotlib.ticker import FuncFormatter
526+
>>> formatter.scaled[1/(24.*60.)] = FuncFormatter(my_format_function)
511527
"""
512528

513529
# This can be improved by providing some user-level direction on
@@ -536,7 +552,7 @@ def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d'):
536552
1. / 24.: '%H:%M:%S',
537553
1. / (24. * 60.): '%H:%M:%S.%f'}
538554

539-
def __call__(self, x, pos=0):
555+
def __call__(self, x, pos=None):
540556
scale = float(self._locator._get_unit())
541557
fmt = self.defaultfmt
542558

@@ -545,8 +561,13 @@ def __call__(self, x, pos=0):
545561
fmt = self.scaled[k]
546562
break
547563

548-
self._formatter = DateFormatter(fmt, self._tz)
549-
return self._formatter(x, pos)
564+
if isinstance(fmt, six.string_types):
565+
self._formatter = DateFormatter(fmt, self._tz)
566+
return self._formatter(x, pos)
567+
elif six.callable(fmt):
568+
return fmt(x, pos)
569+
else:
570+
raise NotImplementedError()
550571

551572

552573
class rrulewrapper:

0 commit comments

Comments
 (0)
0