如何为使用可变 alpha 创建的 vspans 添加颜色条

How to add a color bar for vspans created with variable alpha

我想用不同程度的红色来表示每个时间元素的不同重要性,并填充那个区域。

示例代码如下所示。

import matplotlib.pyplot as plt
X_example = np.random.rand(400)
importance_values = np.random.rand(400)
plt.figure(figsize=(13,7))
plt.plot(X_example)
for j in range(len(X_example)):
    plt.axvspan(xmin=j, xmax=j+1,facecolor="r",alpha=importance_values[j])

它生成的图表如下:

现在我想在此图中添加一个颜色图来显示,例如浅红色表示低重要性,深红色表示高重要性,就像这样:

在我的情况下我怎样才能做到这一点?

一个解决方案是创建一个 LinearSegmentedColormap,它获取颜色列表并将其转换为 matplotlib colorbar 对象。然后你可以设置“alpha通道”:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
from matplotlib.colorbar import ColorbarBase

X_example = np.random.rand(400)
importance_values = np.random.rand(400)

fig, (ax, cax) = plt.subplots(ncols=2, figsize=(8,5), gridspec_kw={'width_ratios': [1, 0.05]})
ax.plot(X_example, color='b')
for j in range(len(X_example)):
    ax.axvspan(xmin=j, xmax=j+1,facecolor="r",alpha=importance_values[j])
    
N = 20  # the number of colors/alpha-values in the colorbar
cmap = LinearSegmentedColormap.from_list(None, ['r' for i in range(N)], N=N)
alpha_cmap = cmap(np.arange(N))
alpha_cmap[:,-1] = np.linspace(0, 1, N)
alpha_cmap = ListedColormap(alpha_cmap, N=N)

cbar = ColorbarBase(cax, cmap=alpha_cmap, ticks=[0., 1],)
cbar.ax.set_yticklabels(["low importance", "high importance"])

这给出了以下图,其中颜色条的两种颜色具有自定义标签:

您可以创建一个将红色与一系列 alpha 值混合的颜色图:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, to_rgba
from matplotlib.cm import ScalarMappable
import numpy as np

X_example = np.random.rand(400)
importance_values = np.random.rand(400)

fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(X_example)
for j in range(len(X_example)):
    ax.axvspan(xmin=j, xmax=j + 1, facecolor="r", alpha=importance_values[j])
ax.margins(x=0)

cmap = LinearSegmentedColormap.from_list(None, [to_rgba('r', 0), 'r'])
cbar = plt.colorbar(ScalarMappable(cmap=cmap), ticks=[0, 1], pad=0.02)
cbar.ax.set_yticklabels(["low", "high"], fontsize=20)
cbar.ax.set_ylabel("importance", labelpad=-30, fontsize=20)
plt.tight_layout()
plt.show()

水平颜色条示例:

cbar = plt.colorbar(ScalarMappable(cmap=cmap), ticks=[0, 1], orientation='horizontal')
cbar.ax.set_xticklabels(["low", "high"], fontsize=20)
cbar.ax.set_xlabel("importance", labelpad=-15, fontsize=20)