8000 Merge pull request #7896 from anntzer/to_rgba-reject-floatlike-strings · matplotlib/matplotlib@12ec2c1 · GitHub
[go: up one dir, main page]

Skip to content

Commit 12ec2c1

Browse files
authored
Merge pull request #7896 from anntzer/to_rgba-reject-floatlike-strings
Reject floatlike strings in mcolors.to_rgba.
2 parents f41ef96 + 0cad64f commit 12ec2c1

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

lib/matplotlib/colors.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -185,12 +185,14 @@ def _to_rgba_no_colorcycle(c, alpha=None):
185185
pass
186186
raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
187187
# tuple color.
188-
# Python 2.7 / numpy 1.6 apparently require this to return builtin floats,
189-
# not numpy floats.
190-
try:
191-
c = tuple(map(float, c))
192-
except TypeError:
188+
c = np.array(c)
189+
if not np.can_cast(c.dtype, float) or c.ndim != 1:
190+
# Test the dtype explicitly as `map(float, ...)`, `np.array(...,
191+
# float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.
192+
# Test dimensionality to reject single floats.
193193
raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
194+
# Return a tuple to prevent the cached value from being modified.
195+
c = tuple(c.astype(float))
194196
if len(c) not in [3, 4]:
195197
raise ValueError("RGBA sequence should have length 3 or 4")
196198
if len(c) == 3 and alpha is None:

lib/matplotlib/tests/test_colors.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -646,6 +646,10 @@ def test_cn():
646646
def test_conversions():
647647
# to_rgba_array("none") returns a (0, 4) array.
648648
assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4)))
649+
# a list of grayscale levels, not a single color.
650+
assert_array_equal(
651+
mcolors.to_rgba_array([".2", ".5", ".8"]),
652+
np.vstack([mcolors.to_rgba(c) for c in [".2", ".5", ".8"]]))
649653
# alpha is properly set.
650654
assert_equal(mcolors.to_rgba((1, 1, 1), .5), (1, 1, 1, .5))
651655
assert_equal(mcolors.to_rgba(".1", .5), (.1, .1, .1, .5))

0 commit comments

Comments
 (0)
0