From 669c08abe5775106caac4be0e98479630464fa3f Mon Sep 17 00:00:00 2001 From: Jody Klymak Date: Thu, 25 Feb 2021 17:40:32 -0800 Subject: [PATCH] FIX: check for a set during color conversion Co-authored-by: Antony Lee --- lib/matplotlib/colors.py | 15 +++++++++------ lib/matplotlib/tests/test_colors.py | 12 ++++++++++++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index 943008f92afc..1955183b0b52 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -66,7 +66,7 @@ """ import base64 -from collections.abc import Sized +from collections.abc import Sized, Sequence import copy import functools import inspect @@ -364,11 +364,14 @@ def to_rgba_array(c, alpha=None): # Quick path if the whole sequence can be directly converted to a numpy # array in one shot. - lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c} - if lens == {3}: - rgba = np.column_stack([c, np.ones(len(c))]) - elif lens == {4}: - rgba = np.array(c) + if isinstance(c, Sequence): + lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c} + if lens == {3}: + rgba = np.column_stack([c, np.ones(len(c))]) + elif lens == {4}: + rgba = np.array(c) + else: + rgba = np.array([to_rgba(cc) for cc in c]) else: rgba = np.array([to_rgba(cc) for cc in c]) diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index eaa0b34b09ef..fff69da380bf 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -1346,6 +1346,18 @@ def test_2d_to_rgba(): assert rgba_1d == rgba_2d +def test_set_dict_to_rgba(): + # downstream libraries do this... + # note we can't test this because it is not well-ordered + # so just smoketest: + colors = set([(0, .5, 1), (1, .2, .5), (.4, 1, .2)]) + res = mcolors.to_rgba_array(colors) + palette = {"red": (1, 0, 0), "green": (0, 1, 0), "blue": (0, 0, 1)} + res = mcolors.to_rgba_array(palette.values()) + exp = np.eye(3) + np.testing.assert_array_almost_equal(res[:, :-1], exp) + + def test_norm_deepcopy(): norm = mcolors.LogNorm() norm.vmin = 0.0002