Skip to content

Commit

Permalink
improve docstring and add test fot to_rgb(<float>)
Browse files Browse the repository at this point in the history
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 matplotlibgh-2609
  • Loading branch information
Carreau committed Nov 24, 2013
1 parent 432d9d8 commit 70e4a8a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/matplotlib/colors.py
Expand Up @@ -272,10 +272,13 @@ def to_rgb(self, arg):
1) a letter from the set 'rgbcmykw'
2) a hex color string, like '#00FFFF'
3) a standard name, like 'aqua'
4) a float, like '0.4', indicating gray on a 0-1 scale
4) a string representation of a float, like '0.4',
indicating gray on a 0-1 scale
if *arg* is *RGBA*, the *A* will simply be discarded.
"""
# Gray must be a string to distinguish 3-4 grays from RGB or RGBA.

try:
return self.cache[arg]
except KeyError:
Expand Down Expand Up @@ -304,7 +307,7 @@ def to_rgb(self, arg):
if fl < 0 or fl > 1:
raise ValueError(
'gray (string) must be in range 0-1')
color = tuple([fl] * 3)
color = (fl,)*3
elif cbook.iterable(arg):
if len(arg) > 4 or len(arg) < 3:
raise ValueError(
Expand Down
13 changes: 13 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Expand Up @@ -192,6 +192,19 @@ def test_autoscale_masked():
plt.draw()


def test_colors_no_float():
# Gray must be a string to distinguish 3-4 grays from RGB or RGBA.

def gray_from_float_rgb():
return mcolors.colorConverter.to_rgb(0.4)

def gray_from_float_rgba():
return mcolors.colorConverter.to_rgba(0.4)

assert_raises(ValueError, gray_from_float_rgb)
assert_raises(ValueError, gray_from_float_rgba)


if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)

0 comments on commit 70e4a8a

Please sign in to comment.