Skip to content

Commit 01d3635

Browse files
committed
Speedup LinearSegmentedColormap.from_list.
... by special-casing lists-of-rgb(a) tuples in to_rgba_array. This speeds up colorcet's import nearly twofold, from ~430ms to ~250ms on my machine. (colorcet generates a lot of colormaps at import time.)
1 parent 2219872 commit 01d3635

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

lib/matplotlib/colors.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -361,11 +361,20 @@ def to_rgba_array(c, alpha=None):
361361

362362
if len(c) == 0:
363363
return np.zeros((0, 4), float)
364+
365+
# Quick path if the whole sequence can be directly converted to a numpy
366+
# array in one shot.
367+
lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c}
368+
if lens == {3}:
369+
rgba = np.column_stack([c, np.ones(len(c))])
370+
elif lens == {4}:
371+
rgba = np.array(c)
364372
else:
365-
if np.iterable(alpha):
366-
return np.array([to_rgba(cc, aa) for cc, aa in zip(c, alpha)])
367-
else:
368-
return np.array([to_rgba(cc, alpha) for cc in c])
373+
rgba = np.array([to_rgba(cc) for cc in c])
374+
375+
if alpha is not None:
376+
rgba[:, 3] = alpha
377+
return rgba
369378

370379

371380
def to_rgb(c):
@@ -914,13 +923,13 @@ def from_list(name, colors, N=256, gamma=1.0):
914923
else:
915924
vals = np.linspace(0, 1, len(colors))
916925

917-
cdict = dict(red=[], green=[], blue=[], alpha=[])
918-
for val, color in zip(vals, colors):
919-
r, g, b, a = to_rgba(color)
920-
cdict['red'].append((val, r, r))
921-
cdict['green'].append((val, g, g))
922-
cdict['blue'].append((val, b, b))
923-
cdict['alpha'].append((val, a, a))
926+
r, g, b, a = to_rgba_array(colors).T
927+
cdict = {
928+
"red": np.column_stack([vals, r, r]),
929+
"green": np.column_stack([vals, g, g]),
930+
"blue": np.column_stack([vals, b, b]),
931+
"alpha": np.column_stack([vals, a, a]),
932+
}
924933

925934
return LinearSegmentedColormap(name, cdict, N, gamma)
926935

0 commit comments

Comments
 (0)