Skip to content

Commit ff8954c

Browse files
jklymakanntzer
andcommitted
FIX: check for a set during color conversion
Co-authored-by: Antony Lee <anntzer.lee@gmail.com>
1 parent 862efc1 commit ff8954c

File tree

2 files changed

+24
-8
lines changed

2 files changed

+24
-8
lines changed

lib/matplotlib/colors.py

+12-8
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, Set
7070
import copy
7171
import functools
7272
import inspect
@@ -364,14 +364,18 @@ def to_rgba_array(c, alpha=None):
364364

365365
# Quick path if the whole sequence can be directly converted to a numpy
366366
# array in one shot.
367-
lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c}
368-
if lens == {3}:
369-
rgba = np.column_stack([c, np.ones(len(c))])
370-
elif lens == {4}:
371-
rgba = np.array(c)
372-
else:
367+
rgba = None
368+
if isinstance(c, list):
369+
lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c}
370+
if lens == {3}:
371+
rgba = np.column_stack([c, np.ones(len(c))])
372+
elif lens == {4}:
373+
rgba = np.array(c)
374+
else:
375+
rgba = np.array([to_rgba(cc) for cc in c])
376+
if rgba is None:
373377
rgba = np.array([to_rgba(cc) for cc in c])
374-
378+
375379
if alpha is not None:
376380
rgba[:, 3] = alpha
377381
return rgba

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)