8000 ENH: plotting methods can unpack labeled data · matplotlib/matplotlib@1e21903 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1e21903

Browse files
committed
ENH: plotting methods can unpack labeled data
After discussions with Brian Granger, Fernando Perez Peter Wang, Matthew Rocklin and Jake VanderPlas this is a proposal for how to deal with labeled data in matplotlib. The approach taken is that if the optional kwarg 'data' is passed in any other string args/kwargs to the function are replaced be the result `data[k]` if the key exists in `data`, else leave the value as-is.
1 parent 563129c commit 1e21903

File tree

3 files changed

+86
-4
lines changed

3 files changed

+86
-4
lines changed

lib/matplotlib/__init__.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@
115115
import warnings
116116
import contextlib
117117
import distutils.sysconfig
118-
118+
import functools
119119
# cbook must import matplotlib only within function
120120
# definitions, so it is safe to import from it here.
121121
from matplotlib.cbook import is_string_like, mplDeprecation
@@ -1515,6 +1515,43 @@ def test(verbosity=1):
15151515

15161516
test.__test__ = False # nose: this function is not a test
15171517

1518+
1519+
def _replacer(data, key):
1520+
# if key isn't a string don't bother
1521+
if not isinstance(key, six.string_types):
1522+
return key
1523+
# try to use __getitem__
1524+
try:
1525+
return data[key]
1526+
# key does not exist, silently fall back to key
1527+
except KeyError:
1528+
return key
1529+
1530+
1531+
def unpack_labeled_data(func):
1532+
"""
1533+
A decorator to add a 'data' kwarg to any a function. The signature
1534+
of the input function must be ::
1535+
1536+
def foo(ax, *args, **kwargs)
1537+
1538+
so this is suitable for use with Axes methods.
1539+
"""
1540+
@functools.wraps(func)
1541+
def inner(ax, *args, **kwargs):
1542+
data = kwargs.pop('data', None)
1543+
if data is not None:
1544+
if rcParams['unpack_labeled']:
1545+
args = tuple(_replacer(data, a) for a in args)
1546+
kwargs = dict((k, _replacer(data, v))
1547+
for k, v in six.iteritems(kwargs))
1548+
else:
1549+
raise ValueError("Trying to unpack labeled data, but "
1550+
"rcParams['unpack_labeled'] is False")
1551+
1552+
return func(ax, *args, **kwargs)
1553+
return inner
1554+
15181555
verbose.report('matplotlib version %s' % __version__)
15191556
verbose.report('verbose.level %s' % verbose.level)
15201557
verbose.report('interactive is %s' % is_interactive())

0 commit comments

Comments
 (0)
0