X Tutup
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions examples/pylab_examples/legend_demo5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple

fig, (ax1, ax2) = plt.subplots(2, 1)
p1 = ax1.scatter([1],[5], c='r', marker='s', s=100)
p2 = ax1.scatter([3],[2], c='b', marker='o', s=100)

l = ax1.legend([(p1, p2)],['points'], scatterpoints=1,
handler_map={tuple: HandlerTuple(ndivide=0)})

ind = [1,2,3]
pos1 = [1, 3, 2]
neg1 = [2, 1, 4]
width=[0.5, 0.5, 0.5]

rpos1 = ax2.bar(ind, pos1, width=0.5, color='k', label='+1')
rneg1 = ax2.bar(ind, neg1, width=0.5, color='w', hatch='///', label='-1')

l = ax2.legend([(rpos1, rneg1)],['Test'],
handler_map={(rpos1, rneg1): HandlerTuple(ndivide=0, pad=0.)})

plt.show()
34 changes: 28 additions & 6 deletions lib/matplotlib/legend_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,13 +135,14 @@ def get_xdata(self, legend, xdescent, ydescent, width, height, fontsize):
if numpoints > 1:
# we put some pad here to compensate the size of the
# marker
xdata = np.linspace(-xdescent + self._marker_pad * fontsize,
width - self._marker_pad * fontsize,
pad = self._marker_pad * fontsize
xdata = np.linspace(-xdescent + pad,
-xdescent + width - pad,
numpoints)
xdata_marker = xdata
elif numpoints == 1:
xdata = np.linspace(-xdescent, width, 2)
xdata_marker = [0.5 * width - 0.5 * xdescent]
xdata = np.linspace(-xdescent, -xdescent+width, 2)
xdata_marker = [-xdescent + 0.5 * width]

return xdata, xdata_marker

Expand Down Expand Up @@ -538,19 +539,40 @@ class HandlerTuple(HandlerBase):
"""
Handler for Tuple
"""
def __init__(self, **kwargs):
def __init__(self, ndivide=1, pad=None, **kwargs):
self._ndivide = ndivide
self._pad = pad
HandlerBase.__init__(self, **kwargs)

def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):

handler_map = legend.get_legend_handler_map()

if self._ndivide == 0:
ndivide = len(orig_handle)
else:
ndivide = self._ndivide

if self._pad is None:
pad = legend.borderpad * fontsize
else:
pad = self._pad * fontsize

if ndivide > 1:
width = (width - pad*(ndivide - 1)) / ndivide

xds = [xdescent - (width + pad) * i for i in range(ndivide)]
from itertools import cycle
xd_next = cycle(xds).next

a_list = []
for handle1 in orig_handle:
handler = legend.get_legend_handler(handler_map, handle1)
_a_list = handler.create_artists(legend, handle1,
xdescent, ydescent, width, height,
xd_next(), ydescent,
width, height,
fontsize,
trans)
a_list.extend(_a_list)
Expand Down
X Tutup