Skip to content

Raises ValueError on unequal lengths of labels and handles input #24063

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

Closed
wants to merge 5 commits into from
Closed
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
4 changes: 4 additions & 0 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -1261,6 +1261,10 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
handles, labels = args[:2]
extra_args = args[2:]

# Check length of handles and labels is consistent
elif len(handles) != len(labels):
raise ValueError("Number of handles not equal "
"to number of labels.")
else:
raise TypeError('Invalid arguments to legend.')

Expand Down
8 changes: 8 additions & 0 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -970,3 +970,11 @@ def test_ncol_ncols(fig_test, fig_ref):
ncols = 3
fig_test.legend(strings, ncol=ncols)
fig_ref.legend(strings, ncols=ncols)


def test_handles_labels_length(self):
l1 = plt.plot(range(10))
l2 = plt.plot(range(11))
with pytest.raises(ValueError, match="Number of handles not equal "
"to number of labels."):
plt.legend([l1, l2], ['l1', 'l2', 'l3'])