如何使用 axhspan 用不同的 alpha 填充颜色 x

Har*_*riS 2 python matplotlib

我想在两行之间填充红色,红色的 alpha 值根据列表而变化。本质上是红色的自定义渐变,但 Alpha 使红色显得更暗或更亮。

可重现的例子:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(20))
y = [8,9,12,14] # respective y values
a = [0.3,0.1,0.5,0.7]
ax.axhspan(8, 14, alpha=0.5, color='red')

plt.show()
Run Code Online (Sandbox Code Playgroud)

阴谋

这可能有助于确定将 RGB 转换为 RGBA 时所需的颜色。也许有一种方法可以使用 axhspan 在两条线之间映射这些颜色?

from matplotlib.colors import to_rgb
r, g, b = to_rgb('red')
alpha_arr = a
c = [(r, g, b, alpha) for alpha in alpha_arr]
Run Code Online (Sandbox Code Playgroud)

Joh*_*anC 6

要获得平滑的渐变,可以使用插值。为了避免细带和 alpha 的问题,您可以使用imshow(或者可能pcolor)代替:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

a = [0.3, 0.1, 0.5, 0.7]
y = [8, 9, 12, 14]

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14, 5))

ax1.plot(range(20))
bounds = np.linspace(y[0], y[-1], 100)
for b0, b1 in zip(bounds[:-1], bounds[1:]):
    ax1.axhspan(b0, b1, alpha=np.interp((b0 + b1) / 2, y, a), facecolor='red', edgecolor='none')
ax1.set_title('Using many thin axhspans')

ax2.plot(range(20))
xmin, xmax = ax2.get_xlim()
ymin, ymax = ax2.get_ylim()
cmap = LinearSegmentedColormap.from_list('', ['white', 'red'])
ax2.imshow(np.interp(np.linspace(y[0], y[-1], 100), y, a).reshape(-1, 1),
           cmap=cmap, vmin=0, vmax=1,
           extent=[xmin, xmax, y[0], y[-1]], origin='lower',
           interpolation='bilinear', aspect='auto', zorder=-1)
ax2.set_xlim(xmin, xmax)
ax2.set_ylim(ymin, ymax)
ax2.set_title('Using imshow')
fig.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

imshow 与 axhspan 的渐变