8000 ENH: Accept ('color', alpha) tuple to define a color · matplotlib/matplotlib@3649ad5 · GitHub
[go: up one dir, main page]

Skip to content

Co 8000 mmit 3649ad5

Browse files
committed
ENH: Accept ('color', alpha) tuple to define a color
1 parent f10d0d1 commit 3649ad5

File tree

2 files changed

+56
-6
lines changed

2 files changed

+56
-6
lines changed

lib/matplotlib/colors.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,8 @@ def to_rgba(c, alpha=None):
286286
Tuple of floats ``(r, g, b, a)``, where each channel (red, green, blue,
287287
alpha) can assume values between 0 and 1.
288288
"""
289+
if isinstance(c, tuple) and len(c) == 2:
290+
c, alpha = c[0], c[1]
289291
# Special-case nth color syntax because it should not be cached.
290292
if _is_nth_color(c):
291293
prop_cycler = mpl.rcParams['axes.prop_cycle']
@@ -308,13 +310,15 @@ def _to_rgba_no_colorcycle(c, alpha=None):
308310
"""
309311
Convert *c* to an RGBA color, with no support for color-cycle syntax.
310312
311-
If *alpha* is given, force the alpha value of the returned RGBA tuple
312-
to *alpha*. Otherwise, the alpha value from *c* is used, if it has alpha
313-
information, or defaults to 1.
313+
If a valid *alpha* is given, force the alpha value of the returned
314+
RGBA tuple to *alpha*. Otherwise, the alpha value from *c* is used,
315+
if it has alpha information, or defaults to 1.
314316
315317
*alpha* is ignored for the color value ``"none"`` (case-insensitive),
316318
which always maps to ``(0, 0, 0, 0)``.
317319
"""
320+
if alpha is not None and not 0 <= alpha <= 1:
321+
raise ValueError('Alpha must be between 0 and 1, inclusive.')
318322
orig_c = c
319323
if c is np.ma.masked:
320324
return (0., 0., 0., 0.)
@@ -428,6 +432,8 @@ def to_rgba_array(c, alpha=None):
428432
# Special-case inputs that are already arrays, for performance. (If the
429433
# array has the wrong kind or shape, raise the error during one-at-a-time
430434
# conversion.)
435+
if isinstance(c, tuple) and len(c) == 2:
436+
c, alpha = c[0], c[1]
431437
if np.iterable(alpha):
432438
alpha = np.asarray(alpha).ravel()
433439
if (isinstance(c, np.ndarray) and c.dtype.kind in "if"
@@ -464,9 +470,11 @@ def to_rgba_array(c, alpha=None):
464470
return np.array([to_rgba(c, a) for a in alpha], float)
465471
else:
466472
return np.array([to_rgba(c, alpha)], float)
467-
except (ValueError, TypeError):
468-
pass
469-
473+
except (ValueError, TypeError) as e:
474+
if e.__repr__() == "ValueError('Alpha must be between 0 and 1, "\
475+
"inclusive.')":
476+
# ValueError is from _to_rgba_no_colorcycle().
477+
raise e
470478
if isinstance(c, str):
471479
raise ValueError(f"{c!r} is not a valid color value.")
472480

lib/matplotlib/tests/test_colors.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1301,6 +1301,48 @@ def test_to_rgba_array_alpha_array():
13011301
assert_array_equal(c[:, 3], alpha)
13021302

13031303

1304+
@pytest.mark.parametrize('rgba_alpha',
1305+
[('red', 0.5), ('#ff0000', 0.5), ('#f00', 0.5),
1306+
('#ff0000ff', 0.5), ((1.0, 0.0, 0.0, 1.0), 0.5)])
1307+
def test_to_rgba_array_color_alpha_tuple(rgba_alpha):
1308+
"""to_rgba_array() accepts tuple (color, alpha) argument."""
1309+
booleans = mcolors.to_rgba_array(rgba_alpha) \
1310+
== mcolors.to_rgba_array('red', alpha=0.5)
1311+
assert booleans.all()
1312+
1313+
1314+
@pytest.mark.parametrize('rg 8000 ba_alpha',
1315+
[('blue', -2), ('#0000ff', -2), ('#00f', -2),
1316+
('#0000ffff', 2), ((0.0, 0.0, 1.0, 1.0), 2)])
1317+
def test_to_rgba_array_color_alpha_tuple_invalid_alpha(rgba_alpha):
1318+
"""
1319+
to_rgba_array() rejects tuple (color, alpha) argument when
1320+
alpha is not between 0 and 1.
1321+
"""
1322+
with pytest.raises(ValueError, match='Alpha must be between 0 and 1,'):
1323+
mcolors.to_rgba_array(rgba_alpha)
1324+
1325+
1326+
@pytest.mark.parametrize('rgba_alpha',
1327+
[('red', 0.5), ('#ff0000', 0.5), ('#f00', 0.5),
1328+
('#ff0000ff', 0.5), ((1.0, 0.0, 0.0, 1.0), 0.5)])
1329+
def test_to_rgba_color_alpha_tuple(rgba_alpha):
1330+
"""to_rgba() accepts tuple (color, alpha) argument."""
1331+
assert mcolors.to_rgba(rgba_alpha) == mcolors.to_rgba('red', alpha=0.5)
1332+
1333+
1334+
@pytest.mark.parametrize('rgba_alpha',
1335+
[('blue', -2), ('#0000ff', -2), ('#00f', -2),
1336+
('#0000ffff', 2), ((0.0, 0.0, 1.0, 1.0), 2)])
1337+
def test_to_rgba_color_alpha_tuple_invalid_alpha(rgba_alpha):
1338+
"""
1339+
to_rgba() rejects tuple (color, alpha) argument when alpha
1340+
is not between 0 and 1.
1341+
"""
1342+
with pytest.raises(ValueError, match='Alpha must be between 0 and 1'):
1343+
mcolors.to_rgba(rgba_alpha)
1344+
1345+
13041346
def test_failed_conversions():
13051347
with pytest.raises(ValueError):
13061348
mcolors.to_rgba('5')

0 commit comments

Comments
 (0)
0