Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Backport PR #28436 on branch v3.9.x (Fix is_color_like for 2-tuple of strings and fix to_rgba for (nth_color, alpha)) #28438

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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']
Expand Down Expand Up @@ -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
Expand Down
15 changes: 14 additions & 1 deletion lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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', [
Expand Down Expand Up @@ -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
Loading