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

Skip to content

Commit ffe8ed4

Browse files
leejjoonJulian Mehne
authored andcommitted
modify legend_hadler.HandlerTuple to display multiple handles side-by-side.
1 parent 766efaa commit ffe8ed4

2 files changed

Lines changed: 45 additions & 2 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import matplotlib.pyplot as plt
2+
from matplotlib.legend_handler import HandlerTuple
3+
4+
fig, (ax1, ax2) = plt.subplots(2, 1)
5+
p1 = ax1.scatter([1],[5], c='r', marker='s', s=100)
6+
p2 = ax1.scatter([3],[2], c='b', marker='o', s=100)
7+
8+
l = ax1.legend([(p1, p2)],['points'], scatterpoints=1,
9+
handler_map={tuple: HandlerTuple(ndivide=0)})
10+
11+
ind = [1,2,3]
12+
pos1 = [1, 3, 2]
13+
neg1 = [2, 1, 4]
14+
width=[0.5, 0.5, 0.5]
15+
16+
rpos1 = ax2.bar(ind, pos1, width=0.5, color='k', label='+1')
17+
rneg1 = ax2.bar(ind, neg1, width=0.5, color='w', hatch='///', label='-1')
18+
19+
l = ax2.legend([(rpos1, rneg1)],['Test'],
20+
handler_map={(rpos1, rneg1): HandlerTuple(ndivide=0, pad=0.)})
21+
22+
plt.show()

lib/matplotlib/legend_handler.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -568,19 +568,40 @@ class HandlerTuple(HandlerBase):
568568
"""
569569
Handler for Tuple
570570
"""
571-
def __init__(self, **kwargs):
571+
def __init__(self, ndivide=1, pad=None, **kwargs):
572+
self._ndivide = ndivide
573+
self._pad = pad
572574
HandlerBase.__init__(self, **kwargs)
573575

574576
def create_artists(self, legend, orig_handle,
575577
xdescent, ydescent, width, height, fontsize,
576578
trans):
577579

578580
handler_map = legend.get_legend_handler_map()
581+
582+
if self._ndivide == 0:
583+
ndivide = len(orig_handle)
584+
else:
585+
ndivide = self._ndivide
586+
587+
if self._pad is None:
588+
pad = legend.borderpad * fontsize
589+
else:
590+
pad = self._pad * fontsize
591+
592+
if ndivide > 1:
593+
width = (width - pad*(ndivide - 1)) / ndivide
594+
595+
xds = [xdescent - (width + pad) * i for i in range(ndivide)]
596+
from itertools import cycle
597+
xd_next = cycle(xds).next
598+
579599
a_list = []
580600
for handle1 in orig_handle:
581601
handler = legend.get_legend_handler(handler_map, handle1)
582602
_a_list = handler.create_artists(legend, handle1,
583-
xdescent, ydescent, width, height,
603+
xd_next(), ydescent,
604+
width, height,
584605
fontsize,
585606
trans)
586607
a_list.extend(_a_list)

0 commit comments

Comments
 (0)