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

Skip to content

Commit 12a4b77

Browse files
committed
add example
1 parent 944f13a commit 12a4b77

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
"""
2+
==========================================
3+
Alpha parameter behavior with different image types
4+
==========================================
5+
6+
Demonstrate how the alpha parameter interacts with different image data types
7+
(2D arrays, RGB, RGBA) and colormaps in matplotlib's imshow function.
8+
9+
This example shows the behavior of the alpha parameter when applied to:
10+
- 2D scalar data with default colormap
11+
- 2D scalar data with custom alpha-aware colormap
12+
- RGB images
13+
- RGBA images with existing alpha channels
14+
15+
The alpha parameter can be:
16+
- None (default, no transparency)
17+
- A scalar float (uniform transparency)
18+
- A 2D array (per-pixel transparency)
19+
"""
20+
21+
import matplotlib.pyplot as plt
22+
import numpy as np
23+
24+
from matplotlib.colors import ListedColormap
25+
26+
# Fixing random state for reproducibility
27+
np.random.seed(19680801)
28+
29+
fig, axs = plt.subplots(3, 4, figsize=(12, 10), layout="compressed")
30+
31+
# Set red background to make transparency visible
32+
for ax in axs.flat:
33+
ax.set(facecolor="red", xticks=[], yticks=[])
34+
35+
# Create test data
36+
mapped = np.array([[0.1, 1.0], [1.0, 0.1]])
37+
rgb = np.repeat(mapped[:, :, np.newaxis], 3, axis=2)
38+
rgba = np.concatenate(
39+
[
40+
rgb,
41+
[
42+
[[1.0], [0.9]],
43+
[[0.8], [0.7]],
44+
],
45+
],
46+
axis=2,
47+
)
48+
49+
alpha_scalar = 0.5
50+
alpha_2d = np.full_like(mapped, alpha_scalar)
51+
52+
# Create a colormap with built-in alpha
53+
cmap_with_alpha = ListedColormap(
54+
np.concatenate(
55+
[plt.cm.viridis.colors, np.full((len(plt.cm.viridis.colors), 1), alpha_scalar)],
56+
axis=1,
57+
),
58+
)
59+
60+
# Test different alpha parameter combinations
61+
for ax, alpha, alpha_type in zip(axs, [None, alpha_scalar, alpha_2d],
62+
["None", "scalar", "array"]):
63+
# 2D data with default colormap
64+
ax[0].imshow(mapped, alpha=alpha)
65+
ax[0].set_title(f"2D data, alpha={alpha_type}")
66+
67+
# 2D data with alpha-aware colormap
68+
ax[1].imshow(mapped, cmap=cmap_with_alpha, alpha=alpha)
69+
ax[1].set_title(f"2D with alpha cmap, alpha={alpha_type}")
70+
71+
# RGB image
72+
ax[2].imshow(rgb, alpha=alpha)
73+
ax[2].set_title(f"RGB image, alpha={alpha_type}")
74+
75+
# RGBA image (existing alpha channel)
76+
ax[3].imshow(rgba, alpha=alpha)
77+
ax[3].set_title(f"RGBA image, alpha={alpha_type}")
78+
79+
plt.suptitle("Alpha parameter behavior with different image types", fontsize=14)
80+
plt.show()

0 commit comments

Comments
 (0)