Skip to content

Commit b20b1d8

Browse files
committed
Pass boxplots labels param to legend & update test
1 parent a9a1abf commit b20b1d8

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

lib/matplotlib/axes/_axes.py

+3
Original file line numberDiff line numberDiff line change
@@ -4007,6 +4007,9 @@ def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,
40074007
if 'color' in boxprops:
40084008
boxprops['edgecolor'] = boxprops.pop('color')
40094009

4010+
if labels:
4011+
boxprops['label'] = labels
4012+
40104013
# if non-default sym value, put it into the flier dictionary
40114014
# the logic for providing the default symbol ('b+') now lives
40124015
# in bxp in the initial value of flierkw

lib/matplotlib/tests/test_legend.py

+24-6
Original file line numberDiff line numberDiff line change
@@ -1393,15 +1393,33 @@ def test_legend_nolabels_draw():
13931393
assert plt.gca().get_legend() is not None
13941394

13951395

1396-
def test_legend_key_patch():
1397-
"""Test that legend key entries are patches"""
1396+
def test_boxplot_legend():
1397+
# Test that boxplot legends handles are patches
1398+
# and labels are generated from boxplot's labels parameter.
13981399
fig, axs = plt.subplots()
13991400
A = 5*np.random.rand(100, 1)
14001401
B = 10*np.random.rand(100, 1) - 5
14011402
C = 7*np.random.rand(100, 1) - 5
1402-
bp0 = axs.boxplot(A, positions=[0], patch_artist=True)
1403-
bp1 = axs.boxplot(B, positions=[1], patch_artist=True)
1404-
bp2 = axs.boxplot(C, positions=[2], patch_artist=True)
1405-
legend = axs.legend(['A', 'B', 'C'])
1403+
labels = ['a', 'b', 'c']
1404+
1405+
bp0 = axs.boxplot(A, positions=[0], patch_artist=True, labels=labels[0])
1406+
bp1 = axs.boxplot(B, positions=[1], patch_artist=True, labels=labels[1])
1407+
bp2 = axs.boxplot(C, positions=[2], patch_artist=True, labels=labels[2])
1408+
# red, blue, green
1409+
colors = [(1.0, 0.0, 0.0, 1), (0.0, 0.0, 1.0, 1), (0.0, 0.5, 0.0, 1)]
1410+
box_list = [bp0, bp1, bp2]
1411+
# Set colors to the boxes
1412+
lbl_index = 0
1413+
for b_plot, color in zip(box_list, colors):
1414+
for patch in b_plot['boxes']:
1415+
patch.set_color(color)
1416+
lbl_index += 1
1417+
1418+
legend = axs.legend()
1419+
index = 0
14061420
for i in legend.legend_handles:
14071421
assert isinstance(i, mpl.patches.Rectangle)
1422+
assert i.get_facecolor() == colors[index]
1423+
assert i.get_edgecolor() == colors[index]
1424+
assert i.get_label() == labels[index]
1425+
index += 1

0 commit comments

Comments
 (0)