如何创建基于 y 值的渐变阶梯图?

How to create a step-plot with a gradient based on y-value?

在 Python matplotlib 中,如何让线条或阶梯图中的线条显示基于 y 值的渐变?

Example plot(在 Tableau 中制作):

带有根据 x 值改变梯度的线的阶梯图代码,改编自 this answer:

fig, ax = plt.subplots(figsize=(10, 4))
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
y = [2, 3, 9, 10, 2, 9, 0, 1, 9, 1, -8]
T = np.linspace(0,1,np.size(x))**2
s = 1
for i in range(0, len(x)-s, s):
    ax.step(x[i:i+s+1], y[i:i+s+1],  marker='.', color=(0.0,0.5,T[i]))
ax.tick_params(axis='both', colors='lightgray', labelsize=8)

以下代码的灵感来自 matplotlib 文档中的 multicolored-line example。首先使用 y-value 绘制水平线段并为其着色。垂直段被细分为小块以单独着色。

范数的

vmin 设置得低一点以避免颜色图的 too-light 范围。

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np

x = np.arange(50)
y = np.random.randint(-3, 4, x.size).cumsum()

fig, ax = plt.subplots()

norm = plt.Normalize(y.min() - y.ptp() * .2, y.max())
cmap = 'inferno_r'  # 'Reds'
horizontal_lines = np.array([x[:-1], y[:-1], x[1:], y[:-1]]).T.reshape(-1, 2, 2)
hor_lc = LineCollection(horizontal_lines, cmap=cmap, norm=norm)
hor_lc.set_array(y[:-1])
ax.add_collection(hor_lc)

factor = 10
long_y0 = np.linspace(y[:-1], y[1:], factor)[:-1, :].T.ravel()
long_y1 = np.linspace(y[:-1], y[1:], factor)[1:, :].T.ravel()
long_x = np.repeat(x[1:], factor - 1)
vertical_lines = np.array([long_x, long_y0, long_x, long_y1]).T.reshape(-1, 2, 2)
ver_lc = LineCollection(vertical_lines, cmap=cmap, norm=norm)
ver_lc.set_array((long_y0 + long_y1) / 2)
ax.add_collection(ver_lc)

ax.scatter(x, y, c=y, cmap=cmap, norm=norm)
plt.autoscale() # needed in case the scatter plot would be omited
plt.show()

这是另一个例子,黑色背景。在这种情况下,避免了颜色图的最暗部分。更改的代码部分是:

y = np.random.randint(-9, 10, x.size)

ax.patch.set_color('black')

norm = plt.Normalize(y.min(), y.max() + y.ptp() * .2)
cmap = 'plasma_r'

这是一个带有 TwoSlopeNorm 和 blue-white-red 颜色图的示例:

from matplotlib.colors import TwoSlopeNorm

y = np.random.uniform(-1, 1, x.size * 10).cumsum()[::10]
y = (y - y.min()) / y.ptp() * 15 - 5

norm = TwoSlopeNorm(vmin=-5, vcenter=0, vmax=10)
cmap = 'bwr'