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

Skip to content

Clarify warning about labels with leading underscores. #22440

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
Feb 12, 2022
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
6 changes: 3 additions & 3 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,9 +406,9 @@ def val_or_rc(val, rc_name):
_lab, _hand = [], []
for label, handle in zip(labels, handles):
if isinstance(label, str) and label.startswith('_'):
_api.warn_external('The handle {!r} has a label of {!r} '
'which cannot be automatically added to'
' the legend.'.format(handle, label))
_api.warn_external(f"The label {label!r} of {handle!r} starts "
"with '_'. It is thus excluded from the "
"legend.")
else:
_lab.append(label)
_hand.append(handle)
Expand Down
14 changes: 14 additions & 0 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,20 @@ def test_various_labels():
ax.legend(numpoints=1, loc='best')


def test_legend_label_with_leading_underscore():
"""
Test that artists with labels starting with an underscore are not added to
the legend, and that a warning is issued if one tries to add them
explicitly.
"""
fig, ax = plt.subplots()
line, = ax.plot([0, 1], label='_foo')
with pytest.warns(UserWarning,
match=r"starts with '_'.*excluded from the legend."):
legend = ax.legend(handles=[line])
assert len(legend.legendHandles) == 0


@image_comparison(['legend_labels_first.png'], remove_text=True)
def test_labels_first():
# test labels to left of markers
Expand Down