Skip to content
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
10 changes: 9 additions & 1 deletion lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def to_rgba(c, alpha=None):

Parameters
----------
c : Matplotlib color
c : Matplotlib color or ``np.ma.masked``

alpha : scalar, optional
If *alpha* is not ``None``, it forces the alpha value, except if *c* is
Expand Down Expand Up @@ -189,6 +189,8 @@ def _to_rgba_no_colorcycle(c, alpha=None):
``"none"`` (case-insensitive), which always maps to ``(0, 0, 0, 0)``.
"""
orig_c = c
if c is np.ma.masked:
return (0., 0., 0., 0.)
if isinstance(c, str):
if c.lower() == "none":
return (0., 0., 0., 0.)
Expand Down Expand Up @@ -260,19 +262,25 @@ def to_rgba_array(c, alpha=None):

If *alpha* is not ``None``, it forces the alpha value. If *c* is
``"none"`` (case-insensitive) or an empty list, an empty array is returned.
If *c* is a masked array, an ndarray is returned with a (0, 0, 0, 0)
row for each masked value or row in *c*.
"""
# Special-case inputs that are already arrays, for performance. (If the
# array has the wrong kind or shape, raise the error during one-at-a-time
# conversion.)
if (isinstance(c, np.ndarray) and c.dtype.kind in "if"
and c.ndim == 2 and c.shape[1] in [3, 4]):
mask = c.mask.any(axis=1) if np.ma.is_masked(c) else None
c = np.ma.getdata(c)
if c.shape[1] == 3:
result = np.column_stack([c, np.zeros(len(c))])
result[:, -1] = alpha if alpha is not None else 1.
elif c.shape[1] == 4:
result = c.copy()
if alpha is not None:
result[:, -1] = alpha
if mask is not None:
result[mask] = 0
if np.any((result < 0) | (result > 1)):
raise ValueError("RGBA values should be within 0-1 range")
return result
Expand Down
10 changes: 10 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,16 @@ def test_conversions():
hex_color


def test_conversions_masked():
x1 = np.ma.array(['k', 'b'], mask=[True, False])
x2 = np.ma.array([[0, 0, 0, 1], [0, 0, 1, 1]])
x2[0] = np.ma.masked
assert mcolors.to_rgba(x1[0]) == (0, 0, 0, 0)
assert_array_equal(mcolors.to_rgba_array(x1),
[[0, 0, 0, 0], [0, 0, 1, 1]])
assert_array_equal(mcolors.to_rgba_array(x2), mcolors.to_rgba_array(x1))


def test_to_rgba_array_single_str():
# single color name is valid
assert_array_equal(mcolors.to_rgba_array("red"), [(1, 0, 0, 1)])
Expand Down