Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit eed5b94

Browse files
committed
FuncFormatter can take func(x) and func(x,pos), and FuncFormatter tests
1 parent 100c7cf commit eed5b94

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

lib/matplotlib/tests/test_ticker.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1041,6 +1041,27 @@ def test_basic(self):
10411041
assert '00002' == tmp_form(2)
10421042

10431043

1044+
class TestFuncFormatter:
1045+
def test_input_x_pos(self):
1046+
func = lambda x, pos : f"{x}+{pos}"
1047+
funcform = mticker.FuncFormatter(func)
1048+
assert "1+2" == funcform(1,2)
1049+
1050+
def text_input_x(self):
1051+
func = lambda x: f"hello {x}"
1052+
funcform = mticker.FuncFormatter(func)
1053+
assert "hello 0" == funcform(0)
1054+
1055+
def test_error(self):
1056+
with pytest.raises(TypeError, match=r"FuncFormatter*"):
1057+
func = lambda x, y, z: " ".join([x, y, z])
1058+
funcform = mticker.FuncFormatter(func)
1059+
funcform(1,2,3)
1060+
1061+
def test_built_in(self):
1062+
funcform = mticker.FuncFormatter("{} hi!".format)
1063+
assert "42 hi!" == funcform(42)
1064+
10441065
class TestStrMethodFormatter:
10451066
test_data = [
10461067
('{x:05d}', (2,), '00002'),

lib/matplotlib/ticker.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@
168168
import logging
169169
import locale
170170
import math
171+
import inspect
171172
from numbers import Integral
172173

173174
import numpy as np
@@ -377,19 +378,34 @@ class FuncFormatter(Formatter):
377378
"""
378379
Use a user-defined function for formatting.
379380
380-
The function should take in two inputs (a tick value ``x`` and a
381-
position ``pos``), and return a string containing the corresponding
382-
tick label.
381+
The function can take in at most two inputs (a required tick value ``x`` and
382+
an optional position ``pos``), and must return a string containing the
383+
corresponding tick label.
383384
"""
384385
def __init__(self, func):
385-
self.func = func
386+
try:
387+
self.nargs = len(inspect.signature(func).parameters)
388+
if self.nargs == 2:
389+
self.func = func
390+
elif self.nargs == 1:
391+
def func_pos(x, pos):
392+
return func(x)
393+
self.func = func_pos
394+
else:
395+
raise TypeError("""FuncFormatter functions take at most
396+
2 parameters: x (required), pos (optional)""")
397+
except ValueError as e:
398+
#built ins like str.format don't have signatures
399+
self.func = func
400+
386401

387402
def __call__(self, x, pos=None):
388403
"""
389404
Return the value of the user defined function.
390405
391406
*x* and *pos* are passed through as-is.
392407
"""
408+
393409
return self.func(x, pos)
394410

395411

0 commit comments

Comments
 (0)