Skip to content

Commit fa73bc0

Browse files
authored
Merge pull request #19583 from jklymak/fix-check-set-colors
FIX: check for a set during color conversion
2 parents b0a840d + 669c08a commit fa73bc0

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

lib/matplotlib/colors.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@
6666
"""
6767

6868
import base64
69-
from collections.abc import Sized
69+
from collections.abc import Sized, Sequence
7070
import copy
7171
import functools
7272
import inspect
@@ -373,11 +373,14 @@ def to_rgba_array(c, alpha=None):
373373

374374
# Quick path if the whole sequence can be directly converted to a numpy
375375
# array in one shot.
376-
lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c}
377-
if lens == {3}:
378-
rgba = np.column_stack([c, np.ones(len(c))])
379-
elif lens == {4}:
380-
rgba = np.array(c)
376+
if isinstance(c, Sequence):
377+
lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c}
378+
if lens == {3}:
379+
rgba = np.column_stack([c, np.ones(len(c))])
380+
elif lens == {4}:
381+
rgba = np.array(c)
382+
else:
383+
rgba = np.array([to_rgba(cc) for cc in c])
381384
else:
382385
rgba = np.array([to_rgba(cc) for cc in c])
383386

lib/matplotlib/tests/test_colors.py

+12
Original file line numberDiff line numberDiff line change
@@ -1346,6 +1346,18 @@ def test_2d_to_rgba():
13461346
assert rgba_1d == rgba_2d
13471347

13481348

1349+
def test_set_dict_to_rgba():
1350+
# downstream libraries do this...
1351+
# note we can't test this because it is not well-ordered
1352+
# so just smoketest:
1353+
colors = set([(0, .5, 1), (1, .2, .5), (.4, 1, .2)])
1354+
res = mcolors.to_rgba_array(colors)
1355+
palette = {"red": (1, 0, 0), "green": (0, 1, 0), "blue": (0, 0, 1)}
1356+
res = mcolors.to_rgba_array(palette.values())
1357+
exp = np.eye(3)
1358+
np.testing.assert_array_almost_equal(res[:, :-1], exp)
1359+
1360+
13491361
def test_norm_deepcopy():
13501362
norm = mcolors.LogNorm()
13511363
norm.vmin = 0.0002

0 commit comments

Comments
 (0)