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

Skip to content

Commit 0abac25

Browse files
afvincentanntzer
authored andcommitted
introduce default monolithic legend handler for Line2D
1 parent f8f6939 commit 0abac25

1 file changed

Lines changed: 59 additions & 2 deletions

File tree

lib/matplotlib/legend_handler.py

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

206206

207-
class HandlerLine2D(HandlerNpoints):
207+
class HandlerLine2DCompound(HandlerNpoints):
208208
"""
209-
Handler for `.Line2D` instances.
209+
Original handler for `.Line2D` instances, that relies on combining
210+
a line-only with a marker-only artist.
210211
"""
211212
def __init__(self, marker_pad=0.3, numpoints=None, **kwargs):
212213
"""
@@ -252,6 +253,62 @@ def create_artists(self, legend, orig_handle,
252253
return [legline, legline_marker]
253254

254255

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

0 commit comments

Comments
 (0)