Skip to content

Commit f3b82c1

Browse files
committed
fix issue 6921 and add tests
Fix Error: local variable 'xdata' referenced before assignment" in legend_handler.py
1 parent 6d3610b commit f3b82c1

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

lib/matplotlib/legend_handler.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -147,22 +147,20 @@ def get_numpoints(self, legend):
147147

148148
def get_xdata(self, legend, xdescent, ydescent, width, height, fontsize):
149149
numpoints = self.get_numpoints(legend)
150-
151150
if numpoints > 1:
152-
# we put some pad here to compensate the size of the
153-
# marker
151+
# we put some pad here to compensate the size of the marker
154152
pad = self._marker_pad * fontsize
155153
xdata = np.linspace(-xdescent + pad,
156154
-xdescent + width - pad,
157155
numpoints)
158156
xdata_marker = xdata
159-
elif numpoints == 1:
160-
xdata = np.linspace(-xdescent, -xdescent+width, 2)
157+
else:
158+
xdata = np.linspace(-xdescent, -xdescent + width, 2)
161159
xdata_marker = [-xdescent + 0.5 * width]
162-
163160
return xdata, xdata_marker
164161

165162

163+
166164
class HandlerNpointsYoffsets(HandlerNpoints):
167165
def __init__(self, numpoints=None, yoffsets=None, **kw):
168166
HandlerNpoints.__init__(self, numpoints=numpoints, **kw)

lib/matplotlib/tests/test_legend.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,3 +331,11 @@ def test_linecollection_scaled_dashes():
331331
for oh, lh in zip((lc1, lc2, lc3), (h1, h2, h3)):
332332
assert oh.get_linestyles()[0][1] == lh._dashSeq
333333
assert oh.get_linestyles()[0][0] == lh._dashOffset
334+
335+
336+
def test_handler_numpoints():
337+
'''test legend handler with numponts less than or equal to 1'''
338+
# related to #6921 and PR #8478
339+
fig, ax = plt.subplots()
340+
ax.plot(range(5), label='test')
341+
ax.legend(numpoints=0.5)

0 commit comments

Comments
 (0)