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

Skip to content

Commit dfa19f6

Browse files
[BUG] Warn when legend() receives mismatched handles and labels in 2-argument positional form (#31315)
* Implement warning for mismatched legend handles and labels Add warning for mismatched handles and labels in legend. * Add regression test for legend argument mismatch Add regression test for mismatched handles and labels in legend. * Fix regression test message for legend mismatch * Fix indentation for test_legend_mismatched_positional_args * Update lib/matplotlib/legend.py Co-authored-by: Tim Hoffmann <[email protected]> * Rename test for legend mismatched arguments * Update lib/matplotlib/tests/test_legend.py Co-authored-by: Tim Hoffmann <[email protected]> * Implement warning test for legend handle-label mismatch Added a test to warn on unequal number of handles and labels in legend. * Add test for legend position argument handling * Update warning message for legend handle mismatch * Fix legend creation with list of labels * gracefully handle generators in mismatch warning * Update warning message for legend handle mismatch * Update lib/matplotlib/legend.py Co-authored-by: Tim Hoffmann <[email protected]> --------- Co-authored-by: Tim Hoffmann <[email protected]>
1 parent 02b42db commit dfa19f6

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

lib/matplotlib/legend.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1385,6 +1385,11 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
13851385

13861386
elif len(args) == 2: # 2 args: user defined handles and labels.
13871387
handles, labels = args[:2]
1388+
if (hasattr(handles, "__len__") and hasattr(labels, "__len__")
1389+
and len(handles) != len(labels)):
1390+
_api.warn_external(f"Mismatched number of handles and labels: "
1391+
f"len(handles) = {len(handles)} "
1392+
f"len(labels) = {len(labels)}")
13881393

13891394
else:
13901395
raise _api.nargs_error('legend', '0-2', len(args))

lib/matplotlib/tests/test_legend.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ def test_hatching():
292292
def test_legend_remove():
293293
fig, ax = plt.subplots()
294294
lines = ax.plot(range(10))
295-
leg = fig.legend(lines, "test")
295+
leg = fig.legend(lines, ["test"])
296296
leg.remove()
297297
assert fig.legends == []
298298
leg = ax.legend("test")
@@ -424,6 +424,15 @@ def test_parasite(self):
424424
plt.legend()
425425
Legend.assert_called_with(host, [p1, p2], ['Density', 'Temperature'])
426426

427+
def test_legend_warns_on_unequal_number_of_handles_and_labels(self):
428+
fig, ax = plt.subplots()
429+
line1, = ax.plot([1, 2])
430+
line2, = ax.plot([3, 4])
431+
with pytest.warns(UserWarning, match="Mismatched number of handles and labels"):
432+
ax.legend([line1, line2], ['only_one']) # 2 handles, 1 label
433+
with pytest.warns(UserWarning, match="Mismatched number of handles and labels"):
434+
ax.legend([line1], ['label_a', 'label_b']) # 1 handle, 2 labels
435+
427436

428437
class TestLegendFigureFunction:
429438
# Tests the legend function for figure

0 commit comments

Comments
 (0)