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

Skip to content

Commit 4f9458d

Browse files
authored
Merge pull request #10263 from jklymak/fix-legend-ordereddict
FIX: (re-allow) legend OrderedDict handles and labels...
2 parents 0db0992 + 3d65ca1 commit 4f9458d

2 files changed

Lines changed: 29 additions & 8 deletions

File tree

lib/matplotlib/legend.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -589,14 +589,17 @@ def __init__(self, parent, handles, labels,
589589
setattr(self, name, value)
590590
del locals_view
591591
# trim handles and labels if illegal label...
592-
for label, handle in zip(labels[:], handles[:]):
593-
if (isinstance(label, six.string_types) and
594-
label.startswith('_')):
595-
warnings.warn('The handle {!r} has a label of {!r} which '
596-
'cannot be automatically added to the '
597-
'legend.'.format(handle, label))
598-
labels.remove(label)
599-
handles.remove(handle)
592+
_lab, _hand = [], []
593+
for label, handle in zip(labels, handles):
594+
if (isinstance(label, six.string_types) and
595+
label.startswith('_')):
596+
warnings.warn('The handle {!r} has a label of {!r} which '
597+
'cannot be automatically added to the '
598+
'legend.'.format(handle, label))
599+
else:
600+
_lab.append(label)
601+
_hand.append(handle)
602+
labels, handles = _lab, _hand
600603

601604
handles = list(handles)
602605
if len(handles) < 2:

lib/matplotlib/tests/test_legend.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from unittest import mock
66
except ImportError:
77
import mock
8+
import collections
89
import numpy as np
910
import pytest
1011

@@ -53,6 +54,23 @@ def test_legend_kwdocstrings():
5354
assert stleg == stfig
5455

5556

57+
def test_legend_ordereddict():
58+
# smoketest that ordereddict inputs work...
59+
60+
X = np.random.randn(10)
61+
Y = np.random.randn(10)
62+
labels = ['a'] * 5 + ['b'] * 5
63+
colors = ['r'] * 5 + ['g'] * 5
64+
65+
fig, ax = plt.subplots()
66+
for x, y, label, color in zip(X, Y, labels, colors):
67+
ax.scatter(x, y, label=label, c=color)
68+
69+
handles, labels = ax.get_legend_handles_labels()
70+
legend = collections.OrderedDict(zip(labels, handles))
71+
ax.legend(legend.values(), legend.keys(), loc=6, bbox_to_anchor=(1, .5))
72+
73+
5674
@image_comparison(baseline_images=['legend_auto1'], remove_text=True)
5775
def test_legend_auto1():
5876
'Test automatic legend placement'

0 commit comments

Comments
 (0)