在 2D 图像中混合透明度和颜色#

混合透明度和颜色以突出显示数据的一部分,使用 imshow。

一个常见的 matplotlib.pyplot.imshow 用途是绘制 2D 统计图。该函数可以轻松地将 2D 矩阵可视化为图像,并向输出添加透明度。例如,可以绘制统计量(例如 t 统计量)并根据其 p 值对每个像素的透明度进行颜色编码。本示例演示了如何实现这种效果。

首先,我们将生成一些数据,在本例中,我们将创建 2D 网格中的两个 2D "斑点"。一个斑点将为正,另一个将为负。

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.colors import Normalize


def normal_pdf(x, mean, var):
    return np.exp(-(x - mean)**2 / (2*var))


# Generate the space in which the blobs will live
xmin, xmax, ymin, ymax = (0, 100, 0, 100)
n_bins = 100
xx = np.linspace(xmin, xmax, n_bins)
yy = np.linspace(ymin, ymax, n_bins)

# Generate the blobs. The range of the values is roughly -.0002 to .0002
means_high = [20, 50]
means_low = [50, 60]
var = [150, 200]

gauss_x_high = normal_pdf(xx, means_high[0], var[0])
gauss_y_high = normal_pdf(yy, means_high[1], var[0])

gauss_x_low = normal_pdf(xx, means_low[0], var[1])
gauss_y_low = normal_pdf(yy, means_low[1], var[1])

weights = (np.outer(gauss_y_high, gauss_x_high)
           - np.outer(gauss_y_low, gauss_x_low))

# We'll also create a grey background into which the pixels will fade
greys = np.full((*weights.shape, 3), 70, dtype=np.uint8)

# First we'll plot these blobs using ``imshow`` without transparency.
vmax = np.abs(weights).max()
imshow_kwargs = {
    'vmax': vmax,
    'vmin': -vmax,
    'cmap': 'RdYlBu',
    'extent': (xmin, xmax, ymin, ymax),
}

fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, **imshow_kwargs)
ax.set_axis_off()
image transparency blend

混合透明度#

使用 matplotlib.pyplot.imshow 绘制数据时包含透明度的最简单方法是将一个与数据形状匹配的数组传递给 alpha 参数。例如,我们将在下面创建一个从左到右渐变的梯度。

# Create an alpha channel of linearly increasing values moving to the right.
alphas = np.ones(weights.shape)
alphas[:, 30:] = np.linspace(1, 0, 70)

# Create the figure and image
# Note that the absolute values may be slightly different
fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, alpha=alphas, **imshow_kwargs)
ax.set_axis_off()
image transparency blend

使用透明度突出显示具有高幅值的数值#

最后,我们将重新创建相同的绘图,但这次我们将使用透明度突出显示数据中的极值。这通常用于突出显示 p 值较小的数据点。我们还将添加等高线以突出显示图像值。

# Create an alpha channel based on weight values
# Any value whose absolute value is > .0001 will have zero transparency
alphas = Normalize(0, .3, clip=True)(np.abs(weights))
alphas = np.clip(alphas, .4, 1)  # alpha value clipped at the bottom at .4

# Create the figure and image
# Note that the absolute values may be slightly different
fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, alpha=alphas, **imshow_kwargs)

# Add contour lines to further highlight different levels.
ax.contour(weights[::-1], levels=[-.1, .1], colors='k', linestyles='-')
ax.set_axis_off()
plt.show()

ax.contour(weights[::-1], levels=[-.0001, .0001], colors='k', linestyles='-')
ax.set_axis_off()
plt.show()
image transparency blend

由 Sphinx-Gallery 生成的画廊