From 2dc3eb6ffdee7d4f8bc2044de5b9da1b7f72cf26 Mon Sep 17 00:00:00 2001 From: hannah Date: Sat, 22 Jun 2024 22:19:39 -0400 Subject: [PATCH] Backport PR #28436: Fix `is_color_like` for 2-tuple of strings and fix `to_rgba` for `(nth_color, alpha)` --- lib/matplotlib/colors.py | 12 ++++++------ lib/matplotlib/tests/test_colors.py | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index c4e5987fdf92..177557b371a6 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -225,7 +225,7 @@ def is_color_like(c): return True try: to_rgba(c) - except ValueError: + except (TypeError, ValueError): return False else: return True @@ -296,6 +296,11 @@ def to_rgba(c, alpha=None): Tuple of floats ``(r, g, b, a)``, where each channel (red, green, blue, alpha) can assume values between 0 and 1. """ + if isinstance(c, tuple) and len(c) == 2: + if alpha is None: + c, alpha = c + else: + c = c[0] # Special-case nth color syntax because it should not be cached. if _is_nth_color(c): prop_cycler = mpl.rcParams['axes.prop_cycle'] @@ -325,11 +330,6 @@ def _to_rgba_no_colorcycle(c, alpha=None): *alpha* is ignored for the color value ``"none"`` (case-insensitive), which always maps to ``(0, 0, 0, 0)``. """ - if isinstance(c, tuple) and len(c) == 2: - if alpha is None: - c, alpha = c - else: - c = c[0] if alpha is not None and not 0 <= alpha <= 1: raise ValueError("'alpha' must be between 0 and 1, inclusive") orig_c = c diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index 63f2d4f00399..4fd9f86c06e3 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -19,7 +19,7 @@ import matplotlib.scale as mscale from matplotlib.rcsetup import cycler from matplotlib.testing.decorators import image_comparison, check_figures_equal -from matplotlib.colors import to_rgba_array +from matplotlib.colors import is_color_like, to_rgba_array @pytest.mark.parametrize('N, result', [ @@ -1697,3 +1697,16 @@ def test_to_rgba_array_none_color_with_alpha_param(): assert_array_equal( to_rgba_array(c, alpha), [[0., 0., 1., 1.], [0., 0., 0., 0.]] ) + + +@pytest.mark.parametrize('input, expected', + [('red', True), + (('red', 0.5), True), + (('red', 2), False), + (['red', 0.5], False), + (('red', 'blue'), False), + (['red', 'blue'], False), + ('C3', True), + (('C3', 0.5), True)]) +def test_is_color_like(input, expected): + assert is_color_like(input) is expected