8000 Merge pull request #16864 from timhoffm/legend-labels-str2 · matplotlib/matplotlib@53faed9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 53faed9

Browse files
authored
Merge pull request #16864 from timhoffm/legend-labels-str2
Check parameter type for legend(labels)
2 parents da6dfab + a1a99cd commit 53faed9

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

examples/text_labels_and_annotations/custom_legends.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@
3333

3434
fig, ax = plt.subplots()
3535
lines = ax.plot(data)
36-
ax.legend(lines)
36+
ax.legend()
3737

3838
##############################################################################
39-
# Note that one legend item per line was created.
39+
# Note that no legend entries were created.
4040
# In this case, we can compose a legend using Matplotlib objects that aren't
4141
# explicitly tied to the data that was plotted. For example:
4242

lib/matplotlib/legend.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,6 +1163,10 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
11631163
# One argument. User defined labels - automatic handle detection.
11641164
elif len(args) == 1:
11651165
labels, = args
1166+
if any(isinstance(l, Artist) for l in labels):
1167+
raise TypeError("A single argument passed to legend() must be a "
1168+
"list of labels, but found an Artist in there.")
1169+
11661170
# Get as many handles as there are labels.
11671171
handles = [handle for handle, label
11681172
in zip(_get_legend_handles(axs, handlers), labels)]

lib/matplotlib/tests/test_legend.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,13 @@ def test_legend_handle_label(self):
234234
plt.legend(lines, ['hello world'])
235235
Legend.assert_called_with(plt.gca(), lines, ['hello world'])
236236

237+
def test_legend_handles_only(self):
238+
lines = plt.plot(range(10))
239+
with pytest.raises(TypeError, match='but found an Artist'):
240+
# a single arg is interpreted as labels
241+
# it's a common error to just pass handles
242+
plt.legend(lines)
243+
237244
def test_legend_no_args(self):
238245
lines = plt.plot(range(10), label='hello world')
239246
with mock.patch('matplotlib.legend.Legend') as Legend:

0 commit comments

Comments
 (0)
0