Skip to content

Commit 5100378

Browse files
authored
Merge pull request matplotlib#24538 from oscargus/legendhandlers
[Doc] Document legend_handles and legend_handlers
2 parents 2e64a9e + 29c8688 commit 5100378

File tree

6 files changed

+78
-27
lines changed

6 files changed

+78
-27
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
``legend.legendHandles``
2+
~~~~~~~~~~~~~~~~~~~~~~~~
3+
4+
... was undocumented and has been renamed to ``legend_handles``. Using ``legendHandles`` is deprecated.

lib/matplotlib/legend.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -360,12 +360,19 @@ def __init__(
360360
labels : list of str
361361
A list of labels to show next to the artists. The length of handles
362362
and labels should be the same. If they are not, they are truncated
363-
to the smaller of both lengths.
363+
to the length of the shorter list.
364364
365365
Other Parameters
366366
----------------
367367
%(_legend_kw_doc)s
368368
369+
Attributes
370+
----------
371+
legend_handles
372+
List of `.Artist` objects added as legend entries.
373+
374+
.. versionadded:: 3.7
375+
369376
Notes
370377
-----
371378
Users can specify any arbitrary location for the legend using the
@@ -397,7 +404,7 @@ def __init__(
397404
self._fontsize = self.prop.get_size_in_points()
398405

399406
self.texts = []
400-
self.legendHandles = []
407+
self.legend_handles = []
401408
self._legend_title_box = None
402409

403410
#: A dictionary with the extra handler mappings for this Legend
@@ -561,7 +568,7 @@ def val_or_rc(val, rc_name):
561568
labelcolor = mpl.rcParams['text.color']
562569
if isinstance(labelcolor, str) and labelcolor in color_getters:
563570
getter_names = color_getters[labelcolor]
564-
for handle, text in zip(self.legendHandles, self.texts):
571+
for handle, text in zip(self.legend_handles, self.texts):
565572
try:
566573
if handle.get_array() is not None:
567574
continue
@@ -594,6 +601,9 @@ def val_or_rc(val, rc_name):
594601
else:
595602
raise ValueError(f"Invalid labelcolor: {labelcolor!r}")
596603

604+
legendHandles = _api.deprecated('3.7', alternative="legend_handles")(
605+
property(lambda self: self.legend_handles))
606+
597607
def _set_artist_props(self, a):
598608
"""
599609
Set the boilerplate props for artists added to axes.
@@ -838,7 +848,7 @@ def _init_legend_box(self, handles, labels, markerfirst=True):
838848
self._legend_box.set_figure(self.figure)
839849
self._legend_box.axes = self.axes
840850
self.texts = text_list
841-
self.legendHandles = handle_list
851+
self.legend_handles = handle_list
842852

843853
def _auto_legend_data(self):
844854
"""
@@ -885,12 +895,12 @@ def get_frame(self):
885895

886896
def get_lines(self):
887897
r"""Return the list of `~.lines.Line2D`\s in the legend."""
888-
return [h for h in self.legendHandles if isinstance(h, Line2D)]
898+
return [h for h in self.legend_handles if isinstance(h, Line2D)]
889899

890900
def get_patches(self):
891901
r"""Return the list of `~.patches.Patch`\s in the legend."""
892902
return silent_list('Patch',
893-
[h for h in self.legendHandles
903+
[h for h in self.legend_handles
894904
if isinstance(h, Patch)])
895905

896906
def get_texts(self):

lib/matplotlib/legend_handler.py

Lines changed: 48 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,16 @@
99
</tutorials/intermediate/legend_guide>` before reading this documentation.
1010
1111
Legend handlers are expected to be a callable object with a following
12-
signature. ::
12+
signature::
1313
1414
legend_handler(legend, orig_handle, fontsize, handlebox)
1515
1616
Where *legend* is the legend itself, *orig_handle* is the original
17-
plot, *fontsize* is the fontsize in pixels, and *handlebox* is a
18-
OffsetBox instance. Within the call, you should create relevant
17+
plot, *fontsize* is the fontsize in pixels, and *handlebox* is an
18+
`.OffsetBox` instance. Within the call, you should create relevant
1919
artists (using relevant properties from the *legend* and/or
20-
*orig_handle*) and add them into the handlebox. The artists need to
21-
be scaled according to the fontsize (note that the size is in pixel,
20+
*orig_handle*) and add them into the *handlebox*. The artists need to
21+
be scaled according to the *fontsize* (note that the size is in pixels,
2222
i.e., this is dpi-scaled value).
2323
2424
This module includes definition of several legend handler classes
@@ -49,7 +49,7 @@ class HandlerBase:
4949
A base class for default legend handlers.
5050
5151
The derived classes are meant to override *create_artists* method, which
52-
has a following signature.::
52+
has the following signature::
5353
5454
def create_artists(self, legend, orig_handle,
5555
xdescent, ydescent, width, height, fontsize,
@@ -61,6 +61,18 @@ def create_artists(self, legend, orig_handle,
6161
6262
"""
6363
def __init__(self, xpad=0., ypad=0., update_func=None):
64+
"""
65+
Parameters
66+
----------
67+
68+
xpad : float, optional
69+
Padding in x-direction.
70+
ypad : float, optional
71+
Padding in y-direction.
72+
update_func : callable, optional
73+
Function for updating the legend handler properties from another
74+
legend handler, used by `~HandlerBase.update_prop`.
75+
"""
6476
self._xpad, self._ypad = xpad, ypad
6577
self._update_prop_func = update_func
6678

@@ -133,6 +145,26 @@ def legend_artist(self, legend, orig_handle,
133145
def create_artists(self, legend, orig_handle,
134146
xdescent, ydescent, width, height, fontsize,
135147
trans):
148+
"""
149+
Return the legend artists generated.
150+
151+
Parameters
152+
----------
153+
legend : `~matplotlib.legend.Legend`
154+
The legend for which these legend artists are being created.
155+
orig_handle : `~matplotlib.artist.Artist` or similar
156+
The object for which these legend artists are being created.
157+
xdescent, ydescent, width, height : int
158+
The rectangle (*xdescent*, *ydescent*, *width*, *height*) that the
159+
legend artists being created should fit within.
160+
fontsize : int
161+
The fontsize in pixels. The legend artists being created should
162+
be scaled according to the given fontsize.
163+
trans : `~matplotlib.transforms.Transform`
164+
The transform that is applied to the legend artists being created.
165+
Typically from unit coordinates in the handler box to screen
166+
coordinates.
167+
"""
136168
raise NotImplementedError('Derived must override')
137169

138170

@@ -217,7 +249,7 @@ class HandlerLine2DCompound(HandlerNpoints):
217249
def create_artists(self, legend, orig_handle,
218250
xdescent, ydescent, width, height, fontsize,
219251
trans):
220-
252+
# docstring inherited
221253
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
222254
width, height, fontsize)
223255

@@ -276,7 +308,7 @@ class HandlerLine2D(HandlerNpoints):
276308
def create_artists(self, legend, orig_handle,
277309
xdescent, ydescent, width, height, fontsize,
278310
trans):
279-
311+
# docstring inherited
280312
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
281313
width, height, fontsize)
282314

@@ -341,6 +373,7 @@ def _create_patch(self, legend, orig_handle,
341373

342374
def create_artists(self, legend, orig_handle,
343375
xdescent, ydescent, width, height, fontsize, trans):
376+
# docstring inherited
344377
p = self._create_patch(legend, orig_handle,
345378
xdescent, ydescent, width, height, fontsize)
346379
self.update_prop(p, orig_handle, legend)
@@ -374,6 +407,7 @@ def _create_line(orig_handle, width, height):
374407

375408
def create_artists(self, legend, orig_handle,
376409
xdescent, ydescent, width, height, fontsize, trans):
410+
# docstring inherited
377411
if orig_handle.get_fill() or (orig_handle.get_hatch() is not None):
378412
p = self._create_patch(orig_handle, xdescent, ydescent, width,
379413
height)
@@ -404,7 +438,7 @@ def _default_update_prop(self, legend_handle, orig_handle):
404438

405439
def create_artists(self, legend, orig_handle,
406440
xdescent, ydescent, width, height, fontsize, trans):
407-
441+
# docstring inherited
408442
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
409443
width, height, fontsize)
410444
ydata = np.full_like(xdata, (height - ydescent) / 2)
@@ -471,6 +505,7 @@ def create_collection(self, orig_handle, sizes, offsets, offset_transform):
471505
def create_artists(self, legend, orig_handle,
472506
xdescent, ydescent, width, height, fontsize,
473507
trans):
508+
# docstring inherited
474509
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
475510
width, height, fontsize)
476511

@@ -534,7 +569,7 @@ def get_err_size(self, legend, xdescent, ydescent,
534569
def create_artists(self, legend, orig_handle,
535570
xdescent, ydescent, width, height, fontsize,
536571
trans):
537-
572+
# docstring inherited
538573
plotlines, caplines, barlinecols = orig_handle
539574

540575
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
@@ -653,6 +688,7 @@ def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize):
653688
def create_artists(self, legend, orig_handle,
654689
xdescent, ydescent, width, height, fontsize,
655690
trans):
691+
# docstring inherited
656692
markerline, stemlines, baseline = orig_handle
657693
# Check to see if the stemcontainer is storing lines as a list or a
658694
# LineCollection. Eventually using a list will be removed, and this
@@ -730,7 +766,7 @@ def __init__(self, ndivide=1, pad=None, **kwargs):
730766
def create_artists(self, legend, orig_handle,
731767
xdescent, ydescent, width, height, fontsize,
732768
trans):
733-
769+
# docstring inherited
734770
handler_map = legend.get_legend_handler_map()
735771

736772
if self._ndivide is None:
@@ -797,6 +833,7 @@ def get_first(prop_array):
797833

798834
def create_artists(self, legend, orig_handle,
799835
xdescent, ydescent, width, height, fontsize, trans):
836+
# docstring inherited
800837
p = Rectangle(xy=(-xdescent, -ydescent),
801838
width=width, height=height)
802839
self.update_prop(p, orig_handle, legend)

lib/matplotlib/patches.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3331,7 +3331,7 @@ def _get_bracket(self, x0, y0,
33313331
return vertices_arrow, codes_arrow
33323332

33333333
def transmute(self, path, mutation_size, linewidth):
3334-
# Doc-string inherited
3334+
# docstring inherited
33353335
if self._beginarrow_head or self._endarrow_head:
33363336
head_length = self.head_length * mutation_size
33373337
head_width = self.head_width * mutation_size
@@ -3598,7 +3598,7 @@ def __init__(self, head_length=.5, head_width=.5, tail_width=.2):
35983598
super().__init__()
35993599

36003600
def transmute(self, path, mutation_size, linewidth):
3601-
# Doc-string inherited
3601+
# docstring inherited
36023602
x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
36033603

36043604
# divide the path into a head and a tail
@@ -3677,7 +3677,7 @@ def __init__(self, head_length=.4, head_width=.4, tail_width=.4):
36773677
super().__init__()
36783678

36793679
def transmute(self, path, mutation_size, linewidth):
3680-
# Doc-string inherited
3680+
# docstring inherited
36813681
x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
36823682

36833683
# divide the path into a head and a tail
@@ -3766,7 +3766,7 @@ def __init__(self, tail_width=.3, shrink_factor=0.5):
37663766
super().__init__()
37673767

37683768
def transmute(self, path, mutation_size, linewidth):
3769-
# Doc-string inherited
3769+
# docstring inherited
37703770
x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
37713771

37723772
arrow_path = [(x0, y0), (x1, y1), (x2, y2)]

lib/matplotlib/tests/test_legend.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def test_legend_label_with_leading_underscore():
147147
with pytest.warns(UserWarning,
148148
match=r"starts with '_'.*excluded from the legend."):
149149
legend = ax.legend(handles=[line])
150-
assert len(legend.legendHandles) == 0
150+
assert len(legend.legend_handles) == 0
151151

152152

153153
@image_comparison(['legend_labels_first.png'], remove_text=True)
@@ -550,7 +550,7 @@ def test_linecollection_scaled_dashes():
550550
ax.add_collection(lc3)
551551

552552
leg = ax.legend([lc1, lc2, lc3], ["line1", "line2", 'line 3'])
553-
h1, h2, h3 = leg.legendHandles
553+
h1, h2, h3 = leg.legend_handles
554554

555555
for oh, lh in zip((lc1, lc2, lc3), (h1, h2, h3)):
556556
assert oh.get_linestyles()[0] == lh._dash_pattern
@@ -970,7 +970,7 @@ def test_legend_draggable(draggable):
970970
def test_alpha_handles():
971971
x, n, hh = plt.hist([1, 2, 3], alpha=0.25, label='data', color='red')
972972
legend = plt.legend()
973-
for lh in legend.legendHandles:
973+
for lh in legend.legend_handles:
974974
lh.set_alpha(1.0)
975975
assert lh.get_facecolor()[:-1] == hh[1].get_facecolor()[:-1]
976976
assert lh.get_edgecolor()[:-1] == hh[1].get_edgecolor()[:-1]
@@ -1102,7 +1102,7 @@ def test_handlerline2d():
11021102
ax.scatter([0, 1], [0, 1], marker="v")
11031103
handles = [mlines.Line2D([0], [0], marker="v")]
11041104
leg = ax.legend(handles, ["Aardvark"], numpoints=1)
1105-
assert handles[0].get_marker() == leg.legendHandles[0].get_marker()
1105+
assert handles[0].get_marker() == leg.legend_handles[0].get_marker()
11061106

11071107

11081108
def test_subfigure_legend():

lib/mpl_toolkits/mplot3d/tests/test_legend3d.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def test_linecollection_scaled_dashes():
5555
ax.add_collection(lc3)
5656

5757
leg = ax.legend([lc1, lc2, lc3], ['line1', 'line2', 'line 3'])
58-
h1, h2, h3 = leg.legendHandles
58+
h1, h2, h3 = leg.legend_handles
5959

6060
for oh, lh in zip((lc1, lc2, lc3), (h1, h2, h3)):
6161
assert oh.get_linestyles()[0] == lh._dash_pattern
@@ -67,7 +67,7 @@ def test_handlerline3d():
6767
ax.scatter([0, 1], [0, 1], marker="v")
6868
handles = [art3d.Line3D([0], [0], [0], marker="v")]
6969
leg = ax.legend(handles, ["Aardvark"], numpoints=1)
70-
assert handles[0].get_marker() == leg.legendHandles[0].get_marker()
70+
assert handles[0].get_marker() == leg.legend_handles[0].get_marker()
7171

7272

7373
def test_contour_legend_elements():

0 commit comments

Comments
 (0)