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

Skip to content

Commit 0c255a0

Browse files
committed
Fix same_color() for 'none' color and raise ValueError if different numbers of colors are passed
1 parent af7beaa commit 0c255a0

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

lib/matplotlib/colors.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,22 @@ def is_color_like(c):
138138

139139

140140
def same_color(c1, c2):
141-
"""Return whether the colors *c1* and *c2* are the same."""
142-
return (to_rgba_array(c1) == to_rgba_array(c2)).all()
141+
"""
142+
Return whether the colors *c1* and *c2* are the same.
143+
144+
*c1*, *c2* can be single colors or lists/arrays of colors.
145+
"""
146+
c1 = to_rgba_array(c1)
147+
c2 = to_rgba_array(c2)
148+
n1 = max(c1.shape[0], 1) # 'none' results in shape (0, 4), but is 1-elem
149+
n2 = max(c2.shape[0], 1) # 'none' results in shape (0, 4), but is 1-elem
150+
151+
if n1 != n2:
152+
raise ValueError('Different number of elements passed.')
153+
# The following shape test is needed to correctly handle comparisons with
154+
# 'none', which results in a shape (0, 4) array and thus cannot be tested
155+
# via value comparison.
156+
return c1.shape == c2.shape and (c1 == c2).all()
143157

144158

145159
def to_rgba(c, alpha=None):

lib/matplotlib/tests/test_colors.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1118,6 +1118,13 @@ def __add__(self, other):
11181118
def test_same_color():
11191119
assert mcolors.same_color('k', (0, 0, 0))
11201120
assert not mcolors.same_color('w', (1, 1, 0))
1121+
assert mcolors.same_color(['red', 'blue'], ['r', 'b'])
1122+
assert mcolors.same_color('none', 'none')
1123+
assert not mcolors.same_color('none', 'red')
1124+
with pytest.raises(ValueError):
1125+
mcolors.same_color(['r', 'g', 'b'], ['r'])
1126+
with pytest.raises(ValueError):
1127+
mcolors.same_color(['red', 'green'], 'none')
11211128

11221129

11231130
def test_hex_shorthand_notation():

0 commit comments

Comments
 (0)