From 13b8718adeef45ba2267b72fab5cf00836535143 Mon Sep 17 00:00:00 2001 From: Ruth Comer <10599679+rcomer@users.noreply.github.com> Date: Sat, 22 Jun 2024 09:14:08 +0100 Subject: [PATCH] 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 c8b44b2dea14..d99dd91e9cf5 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', [ @@ -1702,3 +1702,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
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: