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

Skip to content

Commit 29dc7eb

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 29dc7eb

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

lib/matplotlib/colors.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -362,10 +362,16 @@ def to_rgba_array(c, alpha=None):
362362
if len(c) == 0:
363363
return np.zeros((0, 4), float)
364364
else:
365-
if np.iterable(alpha):
366-
return np.array([to_rgba(cc, aa) for cc, aa in zip(c, alpha)])
365+
lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c}
366+
if lens == {3}:
367+
rgba = np.column_stack([c, np.ones(len(c))])
368+
elif lens == {4}:
369+
rgba = np.array(c)
367370
else:
368-
return np.array([to_rgba(cc, alpha) for cc in c])
371+
rgba = np.array([to_rgba(cc) for cc in c])
372+
if alpha is not None:
373+
rgba[:, 3] = alpha
374+
return rgba
369375

370376

371377
def to_rgb(c):
@@ -914,13 +920,13 @@ def from_list(name, colors, N=256, gamma=1.0):
914920
else:
915921
vals = np.linspace(0, 1, len(colors))
916922

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))
923+
r, g, b, a = to_rgba_array(colors).T
924+
cdict = {
925+
"red": np.column_stack([vals, r, r]),
926+
"green": np.column_stack([vals, g, g]),
927+
"blue": np.column_stack([vals, b, b]),
928+
"alpha": np.column_stack([vals, a, a]),
929+
}
924930

925931
return LinearSegmentedColormap(name, cdict, N, gamma)
926932

0 commit comments

Comments
 (0)