Skip to content

Commit 1cbf8ff

Browse files
committed
Optimize colors.to_rgba.
In the case where a (r, g, b) / (r, g, b, a) tuple is passed in this PR makes _to_rgba_no_colorcycle ~2x faster (by avoiding converting to ndarray and back to tuple). String inputs are handled earlier and thus unchanged; array inputs are essentially as fast.
1 parent 2555e38 commit 1cbf8ff

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

lib/matplotlib/colors.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
from collections.abc import Sized
6969
import functools
7070
import itertools
71+
from numbers import Number
7172
import re
7273

7374
import numpy as np
@@ -260,16 +261,16 @@ def _to_rgba_no_colorcycle(c, alpha=None):
260261
return c, c, c, alpha if alpha is not None else 1.
261262
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
262263
# tuple color.
263-
c = np.array(c)
264-
if not np.can_cast(c.dtype, float, "same_kind") or c.ndim != 1:
265-
# Test the dtype explicitly as `map(float, ...)`, `np.array(...,
266-
# float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.
267-
# Test dimensionality to reject single floats.
264+
if not np.iterable(c):
268265
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
269-
# Return a tuple to prevent the cached value from being modified.
270-
c = tuple(c.astype(float))
271266
if len(c) not in [3, 4]:
272267
raise ValueError("RGBA sequence should have length 3 or 4")
268+
if not all(isinstance(x, Number) for x in c):
269+
# Checks that don't work: `map(float, ...)`, `np.array(..., float)` and
270+
# `np.array(...).astype(float)` would all convert "0.5" to 0.5.
271+
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
272+
# Return a tuple to prevent the cached value from being modified.
273+
c = tuple(map(float, c))
273274
if len(c) == 3 and alpha is None:
274275
alpha = 1
275276
if alpha is not None:

0 commit comments

Comments
 (0)