Skip to content

Commit 94155fb

Browse files
committed
colors: support variable alpha in colormaps
1 parent 33d64ab commit 94155fb

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

lib/matplotlib/colors.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,7 @@ def __init__(self, name, segmentdata, N=256, gamma=1.0):
624624
625625
segmentdata argument is a dictionary with a red, green and blue
626626
entries. Each entry should be a list of *x*, *y0*, *y1* tuples,
627-
forming rows in a table.
627+
forming rows in a table. Entries for alpha are optional.
628628
629629
Example: suppose you want red to increase from 0 to 1 over
630630
the bottom half, green to do the same over the middle half,
@@ -680,6 +680,9 @@ def _init(self):
680680
self._segmentdata['green'], self._gamma)
681681
self._lut[:-3, 2] = makeMappingArray(self.N,
682682
self._segmentdata['blue'], self._gamma)
683+
if 'alpha' in self._segmentdata:
684+
self._lut[:-3, 3] = makeMappingArray(self.N,
685+
self._segmentdata['alpha'], 1)
683686
self._isinit = True
684687
self._set_extremes()
685688

@@ -711,12 +714,13 @@ def from_list(name, colors, N=256, gamma=1.0):
711714
else:
712715
vals = np.linspace(0., 1., len(colors))
713716

714-
cdict = dict(red=[], green=[], blue=[])
717+
cdict = dict(red=[], green=[], blue=[], alpha=[])
715718
for val, color in zip(vals, colors):
716-
r,g,b = colorConverter.to_rgb(color)
719+
r,g,b,a = colorConverter.to_rgba(color)
717720
cdict['red'].append((val, r, r))
718721
cdict['green'].append((val, g, g))
719722
cdict['blue'].append((val, b, b))
723+
cdict['alpha'].append((val, a, a))
720724

721725
return LinearSegmentedColormap(name, cdict, N, gamma)
722726

@@ -733,7 +737,8 @@ def __init__(self, colors, name = 'from_list', N = None):
733737
734738
*colors*
735739
a list of matplotlib color specifications,
736-
or an equivalent Nx3 floating point array (*N* rgb values)
740+
or an equivalent Nx3 or Nx4 floating point array
741+
(*N* rgb or rgba values)
737742
*name*
738743
a string to identify the colormap
739744
*N*
@@ -774,11 +779,9 @@ def __init__(self, colors, name = 'from_list', N = None):
774779

775780

776781
def _init(self):
777-
rgb = np.array([colorConverter.to_rgb(c)
778-
for c in self.colors], np.float)
782+
rgba = colorConverter.to_rgba_array(self.colors)
779783
self._lut = np.zeros((self.N + 3, 4), np.float)
780-
self._lut[:-3, :-1] = rgb
781-
self._lut[:-3, -1] = 1
784+
self._lut[:-3] = rgba
782785
self._isinit = True
783786
self._set_extremes()
784787

0 commit comments

Comments
 (0)