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

Skip to content

Commit 8c6f70c

Browse files
committed
introduce default monolithic legend handler for Line2D
1 parent f0e3fe7 commit 8c6f70c

File tree

1 file changed

+59
-2
lines changed

1 file changed

+59
-2
lines changed

lib/matplotlib/legend_handler.py

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,9 +203,10 @@ def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize):
203203
return ydata
204204

205205

206-
class HandlerLine2D(HandlerNpoints):
206+
class HandlerLine2DCompound(HandlerNpoints):
207207
"""
208-
Handler for `.Line2D` instances.
208+
Original handler for `.Line2D` instances, that relies on combining
209+
a line-only with a marker-only artist.
209210
"""
210211
def __init__(self, marker_pad=0.3, numpoints=None, **kw):
211212
"""
@@ -255,6 +256,62 @@ def create_artists(self, legend, orig_handle,
255256
return [legline, legline_marker]
256257

257258

259+
class HandlerLine2D(HandlerNpoints):
260+
"""
261+
Handler for `.Line2D` instances.
262+
263+
A class similar to the original handler for `.Line2D` instances but
264+
that uses a monolithic artist rather than using one artist for the
265+
line and another one for the marker(s). NB: the former handler, in
266+
use before Matplotlib 3, is still available as `.HandlerLine2DCompound`.
267+
268+
"""
269+
def __init__(self, marker_pad=0.3, numpoints=None, **kw):
270+
"""
271+
Parameters
272+
----------
273+
marker_pad : float
274+
Padding between points in legend entry.
275+
276+
numpoints : int
277+
Number of points to show in legend entry.
278+
279+
Notes
280+
-----
281+
Any other keyword arguments are given to `HandlerNpoints`.
282+
"""
283+
HandlerNpoints.__init__(self, marker_pad=marker_pad,
284+
numpoints=numpoints, **kw)
285+
286+
def create_artists(self, legend, orig_handle,
287+
xdescent, ydescent, width, height, fontsize,
288+
trans):
289+
290+
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
291+
width, height, fontsize)
292+
293+
markevery = None
294+
if self.get_numpoints(legend) == 1:
295+
# Special case: one wants a single marker in the center
296+
# and a line that extends on both sides. One will use a
297+
# 3 points line, but only mark the #1 (i.e. middle) point.
298+
xdata = np.linspace(xdata[0], xdata[-1], 3)
299+
markevery = [1]
300+
301+
ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
302+
legline = Line2D(xdata, ydata, markevery=markevery)
303+
304+
self.update_prop(legline, orig_handle, legend)
305+
306+
if legend.markerscale != 1:
307+
newsz = legline.get_markersize() * legend.markerscale
308+
legline.set_markersize(newsz)
309+
310+
legline.set_transform(trans)
311+
312+
return [legline]
313+
314+
258315
class HandlerPatch(HandlerBase):
259316
"""
260317
Handler for `.Patch` instances.

0 commit comments

Comments
 (0)