Skip to content

Commit 4583736

Browse files
committed
Add set_alpha colormap method
1 parent dc76d19 commit 4583736

File tree

3 files changed

+171
-107
lines changed

3 files changed

+171
-107
lines changed

proplot/colors.py

Lines changed: 35 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from matplotlib import rcParams
1515
from .internals import ic # noqa: F401
1616
from .internals import docstring, warnings, _not_none
17-
from .utils import to_rgb, to_xyz
17+
from .utils import to_rgb, to_rgba, to_xyz, to_xyza
1818
if hasattr(mcm, '_cmap_registry'):
1919
_cmap_database_attr = '_cmap_registry'
2020
else:
@@ -113,7 +113,7 @@ def _get_channel(color, channel, space='hcl'):
113113
Parameters
114114
----------
115115
color : color-spec
116-
The color. Sanitized with `to_rgb`.
116+
The color. Sanitized with `to_rgba`.
117117
channel : {'hue', 'chroma', 'saturation', 'luminance'}
118118
The HCL channel to be retrieved.
119119
space : {'hcl', 'hpl', 'hsl', 'hsv', 'rgb'}, optional
@@ -622,7 +622,7 @@ def append(self, *args, ratios=None, name=None, N=None, **kwargs):
622622
Relative extent of each component colormap in the merged colormap.
623623
Length must equal ``len(args) + 1``.
624624
625-
For example, ``cmap1.append(cmap2, ratios=[2,1])`` generates
625+
For example, ``cmap1.append(cmap2, ratios=(2, 1))`` generates
626626
a colormap with the left two-thrids containing colors from
627627
``cmap1`` and the right one-third containing colors from ``cmap2``.
628628
name : str, optional
@@ -898,16 +898,27 @@ def save(self, path=None, alpha=True):
898898
fh.write(data)
899899
print(f'Saved colormap to {filename!r}.')
900900

901-
def set_alpha(self, alpha):
901+
def set_alpha(self, alpha, coords=None, ratios=None):
902902
"""
903-
Set the opacity for the entire colormap.
903+
Set the opacity for the entire colormap or set up an opacity gradation.
904904
905905
Parameters
906906
----------
907-
alpha : float
908-
The opacity.
907+
alpha : float or list of float
908+
If float, this is the opacity for the entire colormap. If list of
909+
float, the colormap traverses these opacity values.
910+
coords : list of float, optional
911+
Colormap coordinates for the opacity values. The first and last
912+
coordinates must be ``0`` and ``1``. If `alpha` is not scalar, the
913+
default coordinates are ``np.linspace(0, 1, len(alpha))``.
914+
ratios : list of float, optional
915+
Relative extent of each opacity transition segment. Length should
916+
equal ``len(alpha) + 1``. For example
917+
``cmap.set_alpha((1, 1, 0), ratios=(2, 1))`` creates a transtion from
918+
100 percent to 0 percent opacity in the right *third* of the colormap.
909919
"""
910-
self._segmentdata['alpha'] = [(0, alpha, alpha), (1, alpha, alpha)]
920+
alpha = _make_segmentdata_array(alpha, coords=coords, ratios=ratios)
921+
self._segmentdata['alpha'] = alpha
911922
self._isinit = False
912923

913924
def set_cyclic(self, b):
@@ -1155,7 +1166,7 @@ def from_list(cls, name, colors, ratios=None, **kwargs):
11551166
and not isinstance(colors[0], str)
11561167
):
11571168
coords, colors = zip(*colors)
1158-
colors = [to_rgb(color, alpha=True) for color in colors]
1169+
colors = [to_rgba(color) for color in colors]
11591170

11601171
# Build segmentdata
11611172
keys = ('red', 'green', 'blue', 'alpha')
@@ -1568,9 +1579,9 @@ def from_color(cls, name, color, fade=None, space='hsl', **kwargs):
15681579
side of the colormap (default is ``100``), and the saturation
15691580
channel is held constant throughout the colormap.
15701581
1571-
If RGB tuple, hex string, or named color string, the luminance and
1572-
saturation (but *not* the hue) from this color are used for the
1573-
left-hand side of the colormap.
1582+
If RGB[A] tuple, hex string, or named color string, the luminance,
1583+
saturation, and opacity (but *not* the hue) from this color are used
1584+
for the left-hand side of the colormap.
15741585
space : {'hsl', 'hpl', 'hcl'}, optional
15751586
The colorspace in which the luminance is varied.
15761587
@@ -1584,15 +1595,16 @@ def from_color(cls, name, color, fade=None, space='hsl', **kwargs):
15841595
`PerceptuallyUniformColormap`
15851596
The colormap.
15861597
"""
1587-
hue, saturation, luminance, alpha = to_xyz(color, space, alpha=True)
1598+
hue, saturation, luminance, alpha = to_xyza(color, space)
15881599
if fade is None:
15891600
fade = 100
15901601
if isinstance(fade, Number):
1591-
saturation_fade, luminance_fade = saturation, fade
1602+
alpha_fade, saturation_fade, luminance_fade = alpha, saturation, fade
15921603
else:
1593-
_, saturation_fade, luminance_fade = to_xyz(fade, space)
1604+
_, saturation_fade, luminance_fade, alpha_fade = to_xyza(fade, space)
15941605
return cls.from_hsl(
1595-
name, hue=hue, alpha=alpha, space=space,
1606+
name, hue=hue, space=space,
1607+
alpha=(alpha_fade, alpha),
15961608
saturation=(saturation_fade, saturation),
15971609
luminance=(luminance_fade, luminance),
15981610
**kwargs
@@ -1629,7 +1641,7 @@ def from_hsl(
16291641
``len(colors) - 1``. Larger numbers indicate a slower
16301642
transition, smaller numbers indicate a faster transition.
16311643
1632-
For example, ``luminance=[100,50,0]`` with ``ratios=[2,1]``
1644+
For example, ``luminance=(100, 50, 0)`` with ``ratios=(2, 1)``
16331645
results in a colormap with the transition from luminance ``100``
16341646
to ``50`` taking *twice as long* as the transition from luminance
16351647
``50`` to ``0``.
@@ -1675,7 +1687,7 @@ def from_list(cls, name, colors, ratios=None, **kwargs):
16751687
``len(colors) - 1``. Larger numbers indicate a slower
16761688
transition, smaller numbers indicate a faster transition.
16771689
1678-
For example, ``red=[1,0.5,0]`` with ``ratios=[2,1]``
1690+
For example, ``red=(1, 0.5, 0)`` with ``ratios=(2, 1)``
16791691
results in a colormap with the transition from red ``1``
16801692
to ``0.5`` taking *twice as long* as the transition from red
16811693
``0.5`` to ``0``.
@@ -1695,10 +1707,12 @@ def from_list(cls, name, colors, ratios=None, **kwargs):
16951707
space = kwargs.get('space', 'hsl') # use the builtin default
16961708
if not np.iterable(colors):
16971709
raise ValueError(f'Colors must be iterable, got colors={colors!r}')
1698-
if (np.iterable(colors[0]) and len(colors[0]) == 2
1699-
and not isinstance(colors[0], str)):
1710+
if (
1711+
np.iterable(colors[0]) and len(colors[0]) == 2
1712+
and not isinstance(colors[0], str)
1713+
):
17001714
coords, colors = zip(*colors)
1701-
colors = [to_xyz(color, space, alpha=True) for color in colors]
1715+
colors = [to_xyza(color, space) for color in colors]
17021716

17031717
# Build segmentdata
17041718
keys = ('hue', 'saturation', 'luminance', 'alpha')

proplot/constructor.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
from . import ticker as pticker
2828
from . import scale as pscale
2929
from .config import rc
30-
from .utils import to_rgb
30+
from .utils import to_rgba
3131
from .internals import ic # noqa: F401
3232
from .internals import warnings, _version, _version_cartopy, _version_mpl, _not_none
3333
try:
@@ -555,7 +555,7 @@ def _parse_modification(key, value):
555555
not isinstance(arg, str) and np.iterable(arg)
556556
and all(np.iterable(color) for color in arg)
557557
):
558-
colors = [to_rgb(color, cycle=cycle, alpha=True) for color in arg]
558+
colors = [to_rgba(color, cycle=cycle) for color in arg]
559559
if listmode == 'listed':
560560
cmap = pcolors.ListedColormap(colors, tmp)
561561
elif listmode == 'linear':
@@ -569,7 +569,7 @@ def _parse_modification(key, value):
569569
if creverse:
570570
arg = arg[:-2]
571571
try:
572-
color = to_rgb(arg, cycle=cycle, alpha=True)
572+
color = to_rgba(arg, cycle=cycle)
573573
except (ValueError, TypeError):
574574
message = f'Invalid colormap, color cycle, or color {arg!r}.'
575575
if isinstance(arg, str) and arg[:1] != '#':

0 commit comments

Comments
 (0)