Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 70e4a8a

Browse files
committed
improve docstring and add test fot to_rgb(<float>)
Even if the docstring was saing it, emphasis that to_rgb/to_rgba do not accept float as input, but string representation of a float. As one might be tempted to had float->gray conversion add failing test in case the functionality is added. Side fixes : change tuple([value]*3) to (value,)*3 for speed In [18]: %timeit tuple([0.4]*3) 1000000 loops, best of 3: 505 ns per loop In [19]: %timeit (0.4,)*3 10000000 loops, best of 3: 23.5 ns per loop In [20]: (0.4,)*3 == tuple([0.4]*3) Out[20]: True Closes gh-2609
1 parent 432d9d8 commit 70e4a8a

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

lib/matplotlib/colors.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -272,10 +272,13 @@ def to_rgb(self, arg):
272272
1) a letter from the set 'rgbcmykw'
273273
2) a hex color string, like '#00FFFF'
274274
3) a standard name, like 'aqua'
275-
4) a float, like '0.4', indicating gray on a 0-1 scale
275+
4) a string representation of a float, like '0.4',
276+
indicating gray on a 0-1 scale
276277
277278
if *arg* is *RGBA*, the *A* will simply be discarded.
278279
"""
280+
# Gray must be a string to distinguish 3-4 grays from RGB or RGBA.
281+
279282
try:
280283
return self.cache[arg]
281284
except KeyError:
@@ -304,7 +307,7 @@ def to_rgb(self, arg):
304307
if fl < 0 or fl > 1:
305308
raise ValueError(
306309
'gray (string) must be in range 0-1')
307-
color = tuple([fl] * 3)
310+
color = (fl,)*3
308311
elif cbook.iterable(arg):
309312
if len(arg) > 4 or len(arg) < 3:
310313
raise ValueError(

lib/matplotlib/tests/test_colors.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,19 @@ def test_autoscale_masked():
192192
plt.draw()
193193

194194

195+
def test_colors_no_float():
196+
# Gray must be a string to distinguish 3-4 grays from RGB or RGBA.
197+
198+
def gray_from_float_rgb():
199+
return mcolors.colorConverter.to_rgb(0.4)
200+
201+
def gray_from_float_rgba():
202+
return mcolors.colorConverter.to_rgba(0.4)
203+
204+
assert_raises(ValueError, gray_from_float_rgb)
205+
assert_raises(ValueError, gray_from_float_rgba)
206+
207+
195208
if __name__ == '__main__':
196209
import nose
197210
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)

0 commit comments

Comments
 (0)