8000 Factor out legend/figlegend nargs validation. by anntzer · Pull Request #26189 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Factor out legend/figlegend nargs validation. #26189

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,12 +316,7 @@ def legend(self, *args, **kwargs):
--------
.. plot:: gallery/text_labels_and_annotations/legend.py
"""
handles, labels, extra_args, kwargs = mlegend._parse_legend_args(
[self],
*args,
**kwargs)
if len(extra_args):
raise _api.nargs_error('legend', '0-2', len(args))
handles, labels, kwargs = mlegend._parse_legend_args([self], *args, **kwargs)
self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
self.legend_._remove_method = self._remove_legend
return self.legend_
Expand Down
21 changes: 3 additions & 18 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1128,25 +1128,10 @@ def legend(self, *args, **kwargs):
:ref:`legend_guide` for details.
"""

handles, labels, extra_args, kwargs = mlegend._parse_legend_args(
self.axes,
*args,
**kwargs)
# check for third arg
if len(extra_args):
# _api.warn_deprecated(
# "2.1",
# message="Figure.legend will accept no more than two "
# "positional arguments in the future. Use "
# "'fig.legend(handles, labels, loc=location)' "
# "instead.")
# kwargs['loc'] = extra_args[0]
# extra_args = extra_args[1:]
pass
transform = kwargs.pop('bbox_transform', self.transSubfigure)
handles, labels, kwargs = mlegend._parse_legend_args(self.axes, *args, **kwargs)
# explicitly set the bbox transform if the user hasn't.
l = mlegend.Legend(self, handles, labels, *extra_args,
bbox_transform=transform, **kwargs)
kwargs.setdefault("bbox_transform", self.transSubfigure)
l = mlegend.Legend(self, handles, labels, **kwargs)
self.legends.append(l)
l._remove_method = self.legends.remove
self.stale = True
Expand Down
19 changes: 7 additions & 12 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -1344,16 +1344,13 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
The legend handles.
labels : list of str
The legend labels.
extra_args : tuple
*args* with positional handles and labels removed.
kwargs : dict
*kwargs* with keywords handles and labels removed.

"""
log = logging.getLogger(__name__)

handlers = kwargs.get('handler_map')
extra_args = ()

if (handles is not None or labels is not None) and args:
_api.warn_external("You have mixed positional and keyword arguments, "
Expand All @@ -1371,17 +1368,15 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
handles = [handle for handle, label
in zip(_get_legend_handles(axs, handlers), labels)]

# No arguments - automatically detect labels and handles.
elif len(args) == 0:
elif len(args) == 0: # 0 args: automatically detect labels and handles.
handles, labels = _get_legend_handles_labels(axs, handlers)
if not handles:
log.warning(
"No artists with labels found to put in legend. Note that "
"artists whose label start with an underscore are ignored "
"when legend() is called with no argument.")

# One argument. User defined labels - automatic handle detection.
elif len(args) == 1:
elif len(args) == 1: # 1 arg: user defined labels, automatic handle detection.
labels, = args
if any(isinstance(l, Artist) for l in labels):
raise TypeError("A single argument passed to legend() must be a "
Expand All @@ -1391,10 +1386,10 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
handles = [handle for handle, label
in zip(_get_legend_handles(axs, handlers), labels)]

# Two arguments:
# * user defined handles and labels
else:
elif len(args) == 2: # 2 args: user defined handles and labels.
handles, labels = args[:2]
extra_args = args[2:]

return handles, labels, extra_args, kwargs
else:
raise _api.nargs_error('legend', '0-2', len(args))

return handles, labels, kwargs
12 changes: 2 additions & 10 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,17 +453,9 @@ def test_legend_label_arg(self):
def test_legend_label_three_args(self):
fig, ax = plt.subplots()
lines = ax.plot(range(10))
with mock.patch('matplotlib.legend.Legend') as Legend:
with pytest.raises(TypeError, match="0-2"):
fig.legend(lines, ['foobar'], 'right')
Legend.assert_called_with(fig, lines, ['foobar'], 'right',
bbox_transform=fig.transFigure)

def test_legend_label_three_args_pluskw(self):
# test that third argument and loc= called together give
# Exception
fig, ax = plt.subplots()
lines = ax.plot(range(10))
with pytest.raises(Exception):
with pytest.raises(TypeError, match="0-2"):
fig.legend(lines, ['foobar'], 'right', loc='left')

def test_legend_kw_args(self):
Expand Down
0