8000 Fix string numbers in to_rgba() and is_color_like() · matplotlib/matplotlib@3685562 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3685562

Browse files
committed
Fix string numbers in to_rgba() and is_color_like()
1 parent bc4c4cc commit 3685562

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
lines changed

lib/matplotlib/colors.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,9 +225,14 @@ def _to_rgba_no_colorcycle(c, alpha=None):
225225
return tuple(color)
226226
# string gray.
227227
try:
228-
return (float(c),) * 3 + (alpha if alpha is not None else 1.,)
228+
c = float(c)
229229
except ValueError:
230230
pass
231+
else:
232+
if not (0 <= c <= 1):
233+
raise ValueError(
234+
"String grayscale values must be within 0-1 range")
235+
return (float(c),) * 3 + (alpha if alpha is not None else 1.,)
231236
raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
232237
# tuple color.
233238
c = np.array(c)

lib/matplotlib/tests/test_colors.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -471,12 +471,6 @@ def test_autoscale_masked():
471471
plt.draw()
472472

473473

474-
def test_colors_no_float():
475-
# Gray must be a string to distinguish 3-4 grays from RGB or RGBA.
476-
with pytest.raises(ValueError):
477-
mcolors.to_rgba(0.4)
478-
479-
480474
@image_comparison(baseline_images=['light_source_shading_topo'],
481475
extensions=['png'])
482476
def test_light_source_topo_surface():
@@ -756,6 +750,18 @@ def test_conversions():
756750
hex_color
757751

758752

753+
def test_failed_conversions():
754+
with pytest.raises(ValueError):
755+
mcolors.to_rgba('5')
756+
with pytest.raises(ValueError):
757+
mcolors.to_rgba('-1')
758+
with pytest.raises(ValueError):
759+
mcolors.to_rgba('nan')
760+
with pytest.raises(ValueError):
761+
# Gray must be a string to distinguish 3-4 grays from RGB or RGBA.
762+
mcolors.to_rgba(0.4)
763+
764+
759765
def test_grey_gray():
760766
color_mapping = mcolors._colors_full_map
761767
for k in color_mapping.keys():

0 commit comments

Comments
 (0)
0