From a1a99cdbffffc1a66de122affd7186a4c41d61a7 Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Sat, 21 Mar 2020 17:21:37 +0100 Subject: [PATCH] Check parameter type for legend(labels) --- examples/text_labels_and_annotations/custom_legends.py | 4 ++-- lib/matplotlib/legend.py | 4 ++++ lib/matplotlib/tests/test_legend.py | 7 +++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/examples/text_labels_and_annotations/custom_legends.py b/examples/text_labels_and_annotations/custom_legends.py index 28b73fe65da2..e9f840fe768f 100644 --- a/examples/text_labels_and_annotations/custom_legends.py +++ b/examples/text_labels_and_annotations/custom_legends.py @@ -33,10 +33,10 @@ fig, ax = plt.subplots() lines = ax.plot(data) -ax.legend(lines) +ax.legend() ############################################################################## -# Note that one legend item per line was created. +# Note that no legend entries were created. # In this case, we can compose a legend using Matplotlib objects that aren't # explicitly tied to the data that was plotted. For example: diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index fb47147d152f..611167b075e7 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -1162,6 +1162,10 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs): # One argument. User defined labels - automatic handle detection. elif len(args) == 1: labels, = args + if any(isinstance(l, Artist) for l in labels): + raise TypeError("A single argument passed to legend() must be a " + "list of labels, but found an Artist in there.") + # Get as many handles as there are labels. handles = [handle for handle, label in zip(_get_legend_handles(axs, handlers), labels)] diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index 0e340e7f1e82..a2656a85528a 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -234,6 +234,13 @@ def test_legend_handle_label(self): plt.legend(lines, ['hello world']) Legend.assert_called_with(plt.gca(), lines, ['hello world']) + def test_legend_handles_only(self): + lines = plt.plot(range(10)) + with pytest.raises(TypeError, match='but found an Artist'): + # a single arg is interpreted as labels + # it's a common error to just pass handles + plt.legend(lines) + def test_legend_no_args(self): lines = plt.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.Legend') as Legend: