Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 71f5cf3

Browse filesBrowse files
timhoffmQuLogic
andauthored
Add new method Colormap.with_alpha() (#29525)
We currently do not have a way of adjusting only the transparency of the mapped colors of the artist, e.g. the fill in contourf(). The Artist alpha parameter also affects lines and hatches. The simplest solution is to support creating semi-transparent colormaps, which can then be used via `contourf(..., cmap=plt.colormaps['jet'].with_alpha(0.5))`. See also #29044 (comment). Co-authored-by: Elliott Sales de Andrade <quantum.analyst@gmail.com>
1 parent 05a66bb commit 71f5cf3
Copy full SHA for 71f5cf3

File tree

Expand file treeCollapse file tree

4 files changed

+37
-1
lines changed
Filter options
Expand file treeCollapse file tree

4 files changed

+37
-1
lines changed
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Tuning transparency of colormaps
2+
--------------------------------
3+
The new method `.Colormap.with_alpha` allows to create a new colormap with the same
4+
color values but a new uniform alpha value. This is handy if you want to modify only
5+
the transparency of mapped colors for an Artist.

‎lib/matplotlib/colors.py

Copy file name to clipboardExpand all lines: lib/matplotlib/colors.py
+19Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -943,6 +943,25 @@ def _set_extremes(self):
943943
self._lut[self._i_over] = self._lut[self.N - 1]
944944
self._lut[self._i_bad] = self._rgba_bad
945945

946+
def with_alpha(self, alpha):
947+
"""
948+
Return a copy of the colormap with a new uniform transparency.
949+
950+
Parameters
951+
----------
952+
alpha : float
953+
The alpha blending value, between 0 (transparent) and 1 (opaque).
954+
"""
955+
if not isinstance(alpha, Real):
956+
raise TypeError(f"'alpha' must be numeric or None, not {type(alpha)}")
957+
if not 0 <= alpha <= 1:
958+
ValueError("'alpha' must be between 0 and 1, inclusive")
959+
new_cm = self.copy()
960+
if not new_cm._isinit:
961+
new_cm._init()
962+
new_cm._lut[:, 3] = alpha
963+
return new_cm
964+
946965
def _init(self):
947966
"""Generate the lookup table, ``self._lut``."""
948967
raise NotImplementedError("Abstract class only")

‎lib/matplotlib/colors.pyi

Copy file name to clipboardExpand all lines: lib/matplotlib/colors.pyi
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ class Colormap:
111111
under: ColorType | None = ...,
112112
over: ColorType | None = ...
113113
) -> Colormap: ...
114+
def with_alpha(self, alpha: float) -> Colormap: ...
114115
def is_gray(self) -> bool: ...
115116
def resampled(self, lutsize: int) -> Colormap: ...
116117
def reversed(self, name: str | None = ...) -> Colormap: ...

‎lib/matplotlib/tests/test_colors.py

Copy file name to clipboardExpand all lines: lib/matplotlib/tests/test_colors.py
+12-1Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import matplotlib.scale as mscale
2121
from matplotlib.rcsetup import cycler
2222
from matplotlib.testing.decorators import image_comparison, check_figures_equal
23-
from matplotlib.colors import is_color_like, to_rgba_array
23+
from matplotlib.colors import is_color_like, to_rgba_array, ListedColormap
2424

2525

2626
@pytest.mark.parametrize('N, result', [
@@ -248,6 +248,17 @@ def test_LinearSegmentedColormap_from_list_bad_under_over():
248248
assert mcolors.same_color(cmap.get_over(), "y")
249249

250250

251+
def test_colormap_with_alpha():
252+
cmap = ListedColormap(["red", "green", ("blue", 0.8)])
253+
cmap2 = cmap.with_alpha(0.5)
254+
# color is the same:
255+
vals = [0, 0.5, 1] # numeric positions that map to the listed colors
256+
assert_array_equal(cmap(vals)[:, :3], cmap2(vals)[:, :3])
257+
# alpha of cmap2 is changed:
258+
assert_array_equal(cmap(vals)[:, 3], [1, 1, 0.8])
259+
assert_array_equal(cmap2(vals)[:, 3], [0.5, 0.5, 0.5])
260+
261+
251262
def test_BoundaryNorm():
252263
"""
253264
GitHub issue #1258: interpolation was failing with numpy

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.