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

Skip to content

Commit a0bcd8c

Browse files
authored
Merge pull request #20788 from greglucas/cbar-2d-alpha
FIX: Check for colorbar creation with multi-dimensional alpha
2 parents d29056c + e616780 commit a0bcd8c

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

lib/matplotlib/colorbar.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,9 @@ def __init__(self, ax, mappable=None, *, cmap=None,
427427
extend = norm.extend
428428
else:
429429
extend = 'neither'
430-
self.alpha = alpha
430+
self.alpha = None
431+
# Call set_alpha to handle array-like alphas properly
432+
self.set_alpha(alpha)
431433
self.cmap = cmap
432434
self.norm = norm
433435
self.values = values
@@ -934,8 +936,13 @@ def set_label(self, label, *, loc=None, **kwargs):
934936
self.stale = True
935937

936938
def set_alpha(self, alpha):
937-
"""Set the transparency between 0 (transparent) and 1 (opaque)."""
938-
self.alpha = alpha
939+
"""
940+
Set the transparency between 0 (transparent) and 1 (opaque).
941+
942+
If an array is provided, *alpha* will be set to None to use the
943+
transparency values associated with the colormap.
944+
"""
945+
self.alpha = None if isinstance(alpha, np.ndarray) else alpha
939946

940947
def _set_scale(self, scale, **kwargs):
941948
"""

lib/matplotlib/tests/test_colorbar.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,18 @@ def test_mappable_no_alpha():
604604
plt.draw()
605605

606606

607+
def test_mappable_2d_alpha():
608+
fig, ax = plt.subplots()
609+
x = np.arange(1, 5).reshape(2, 2)/4
610+
pc = ax.pcolormesh(x, alpha=x)
611+
cb = fig.colorbar(pc, ax=ax)
612+
# The colorbar's alpha should be None and the mappable should still have
613+
# the original alpha array
614+
assert cb.alpha is None
615+
assert pc.get_alpha() is x
616+
fig.draw_no_output()
617+
618+
607619
def test_colorbar_label():
608620
"""
609621
Test the label parameter. It should just be mapped to the xlabel/ylabel of

0 commit comments

Comments
 (0)