8000 Issues warnings for legend handles without handlers by kdpenner · Pull Request #20470 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Issues warnings for legend handles without handlers #20470

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
Mar 3, 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
25 changes: 18 additions & 7 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
from matplotlib.collections import (
Collection, CircleCollection, LineCollection, PathCollection,
PolyCollection, RegularPolyCollection)
from matplotlib.text import Text
from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
from matplotlib.transforms import BboxTransformTo, BboxTransformFrom
from matplotlib.offsetbox import (
Expand Down Expand Up @@ -740,11 +741,12 @@ def _init_legend_box(self, handles, labels, markerfirst=True):
handler = self.get_legend_handler(legend_handler_map, orig_handle)
if handler is None:
_api.warn_external(
"Legend does not support {!r} instances.\nA proxy artist "
"may be used instead.\nSee: "
"https://matplotlib.org/users/legend_guide.html"
"#creating-artists-specifically-for-adding-to-the-legend-"
"aka-proxy-artists".format(orig_handle))
"Legend does not support handles for {0} "
"instances.\nA proxy artist may be used "
"instead.\nSee: https://matplotlib.org/"
"stable/tutorials/intermediate/legend_guide.html"
"#controlling-the-legend-entries".format(
type(orig_handle).__name__))
# No handle for this artist, so we just defer to None.
handle_list.append(None)
else:
Expand Down Expand Up @@ -1074,14 +1076,14 @@ def _get_legend_handles(axs, legend_handler_map=None):
for ax in axs:
handles_original += [
*(a for a in ax._children
if isinstance(a, (Line2D, Patch, Collection))),
if isinstance(a, (Line2D, Patch, Collection, Text))),
*ax.containers]
# support parasite axes:
if hasattr(ax, 'parasites'):
for axx in ax.parasites:
handles_original += [
*(a for a in axx._children
if isinstance(a, (Line2D, Patch, Collection))),
if isinstance(a, (Line2D, Patch, Collection, Text))),
*axx.containers]

handler_map = {**Legend.get_default_handler_map(),
Expand All @@ -1091,6 +1093,15 @@ def _get_legend_handles(axs, legend_handler_map=None):
label = handle.get_label()
if label != '_nolegend_' and has_handler(handler_map, handle):
yield handle
elif (label not in ['_nolegend_', ''] and
not has_handler(handler_map, handle)):
_api.warn_external(
"Legend does not support handles for {0} "
"instances.\nSee: https://matplotlib.org/stable/"
"tutorials/intermediate/legend_guide.html"
"#implementing-a-custom-legend-handler".format(
type(handle).__name__))
continue


def _get_legend_handles_labels(axs, legend_handler_map=None):
Expand Down
9 changes: 9 additions & 0 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,15 @@ def test_handler_numpoints():
ax.legend(numpoints=0.5)


def test_text_nohandler_warning():
"""Test that Text artists with labels raise a warning"""
fig, ax = plt.subplots()
ax.text(x=0, y=0, s="text", label="label")
with pytest.warns(UserWarning) as record:
ax.legend()
assert len(record) == 1


def test_empty_bar_chart_with_legend():
"""Test legend when bar chart is empty with a label."""
# related to issue #13003. Calling plt.legend() should not
Expand Down
3 changes: 3 additions & 0 deletions lib/matplotlib/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ def __init__(self,
"""
Create a `.Text` instance at *x*, *y* with string *text*.

While Text accepts the 'label' keyword argument, by default it is not
added to the handles of a legend.

Valid keyword arguments are:

%(Text:kwdoc)s
Expand Down
0