Skip to content

Commit 9b30845

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

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

lib/matplotlib/colors.py

+10
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,11 @@ 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 and isinstance(c[0], str):
290+
if 0 <= c[1] <= 1:
291+
c, alpha = c[0], c[1]
292+
else:
293+
raise ValueError('Alpha must be between 0 and 1, inclusive.')
289294
# Special-case nth color syntax because it should not be cached.
290295
if _is_nth_color(c):
291296
prop_cycler = mpl.rcParams['axes.prop_cycle']
@@ -428,6 +433,11 @@ def to_rgba_array(c, alpha=None):
428433
# Special-case inputs that are already arrays, for performance. (If the
429434
# array has the wrong kind or shape, raise the error during one-at-a-time
430435
# conversion.)
436+
if isinstance(c, tuple) and len(c) == 2 and isinstance(c[0], str):
437+
if 0 <= c[1] <= 1:
438+
c, alpha = c[0], c[1]
439+
else:
440+
raise ValueError('Alpha must be between 0 and 1, inclusive.')
431441
if np.iterable(alpha):
432442
alpha = np.asarray(alpha).ravel()
433443
if (isinstance(c, np.ndarray) and c.dtype.kind in "if"

lib/matplotlib/tests/test_colors.py

+17
Original file line numberDiff line numberDiff line change
@@ -1301,6 +1301,21 @@ def test_to_rgba_array_alpha_array():
13011301
assert_array_equal(c[:, 3], alpha)
13021302

13031303

1304+
def test_to_rgba_array_color_alpha_tuple():
1305+
booleans = mcolors.to_rgba_array(('red', 0.1)) \
1306+
== mcolors.to_rgba_array('red', alpha=0.1)
1307+
assert booleans.all()
1308+
1309+
1310+
def test_to_rgba_array_raises_error():
1311+
with pytest.raises(ValueError, match='Alpha must be between 0 and 1,'):
1312+
mcolors.to_rgba_array(('blue', 2))
1313+
1314+
1315+
def test_to_rgba_color_alpha_tuple():
1316+
assert mcolors.to_rgba(('red', 0.1)) == mcolors.to_rgba('red', alpha=0.1)
1317+
1318+
13041319
def test_failed_conversions():
13051320
with pytest.raises(ValueError):
13061321
mcolors.to_rgba('5')
@@ -1313,6 +1328,8 @@ def test_failed_conversions():
13131328
with pytest.raises(ValueError):
13141329
# Gray must be a string to distinguish 3-4 grays from RGB or RGBA.
13151330
mcolors.to_rgba(0.4)
1331+
with pytest.raises(ValueError, match='Alpha must be between 0 and 1,'):
1332+
mcolors.to_rgba(('blue', 2))
13161333

13171334

13181335
def test_grey_gray():

0 commit comments

Comments
 (0)