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

Skip to content

Commit 036daed

Browse files
author
Julien Lecoeur
committed
Allow different widths in legends handled by HandlerTuple
1 parent 8b8b560 commit 036daed

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

lib/matplotlib/legend_handler.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -578,18 +578,25 @@ class HandlerTuple(HandlerBase):
578578
The number of sections to divide the legend area into. If None,
579579
use the length of the input tuple. Default is 1.
580580
581-
582581
pad : float, optional
583582
If None, fall back to `legend.borderpad` as the default.
584583
In units of fraction of font size. Default is None.
585584
586-
585+
width_ratios : tuple, optional
586+
The relative width of sections. Must be of length ndivide.
587+
If None, all sections will have the same width. Default is None.
587588
588589
"""
589-
def __init__(self, ndivide=1, pad=None, **kwargs):
590+
def __init__(self, ndivide=1, pad=None, width_ratios=None, **kwargs):
590591

591592
self._ndivide = ndivide
592593
self._pad = pad
594+
595+
if (width_ratios is not None) and (len(width_ratios) == ndivide):
596+
self._width_ratios = width_ratios
597+
else:
598+
self._width_ratios = None
599+
593600
HandlerBase.__init__(self, **kwargs)
594601

595602
def create_artists(self, legend, orig_handle,
@@ -608,10 +615,16 @@ def create_artists(self, legend, orig_handle,
608615
else:
609616
pad = self._pad * fontsize
610617

611-
if ndivide > 1:
612-
width = (width - pad*(ndivide - 1)) / ndivide
618+
if self._width_ratios is not None:
619+
sumratios = sum(self._width_ratios)
620+
widths = [(width - pad * (ndivide - 1)) * ratio / sumratios
621+
for ratio in self._width_ratios]
622+
else:
623+
widths = [(width - pad * (ndivide - 1)) / ndivide
624+
for _ in range(ndivide)]
625+
widths_cycle = cycle(widths)
613626

614-
xds = [xdescent - (width + pad) * i for i in range(ndivide)]
627+
xds = [xdescent - (widths[-i-1] + pad) * i for i in range(ndivide)]
615628
xds_cycle = cycle(xds)
616629

617630
a_list = []
@@ -620,7 +633,8 @@ def create_artists(self, legend, orig_handle,
620633
_a_list = handler.create_artists(legend, handle1,
621634
six.next(xds_cycle),
622635
ydescent,
623-
width, height,
636+
six.next(widths_cycle),
637+
height,
624638
fontsize,
625639
trans)
626640
a_list.extend(_a_list)

0 commit comments

Comments
 (0)