python - 如何轻松地将颜色图应用于线图?

标签 python matplotlib plot colormap

我找到了这个例子multicolored lines生成这些图:

那里的代码使用了 reshaped 连接的 x,y 值的 LineCollection,这看起来相当麻烦。是否没有更简单的方法将颜色图应用于线图?像 plot(x, y, cmap='viridis', Colors=dxdy) 之类的东西?为了澄清起见,我不是在询问使用颜色图来设置多条线的恒定颜色(如所述,例如 here ),而是在询问将颜色图应用到非恒定颜色的线上。

<小时/>

为了完整起见,以下是该示例的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
dydx = np.cos(0.5 * (x[:-1] + x[1:]))  # first derivative

# Create a set of line segments so that we can color them individually
# This creates the points as a N x 1 x 2 array so that we can stack points
# together easily to get the segments. The segments array for line collection
# needs to be (numlines) x (points per line) x 2 (for x and y)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

fig, axs = plt.subplots(2, 1, sharex=True, sharey=True)

# Create a continuous norm to map from data points to colors
norm = plt.Normalize(dydx.min(), dydx.max())
lc = LineCollection(segments, cmap='viridis', norm=norm)
# Set the values used for colormapping
lc.set_array(dydx)
lc.set_linewidth(2)
line = axs[0].add_collection(lc)
fig.colorbar(line, ax=axs[0])

# Use a boundary norm instead
cmap = ListedColormap(['r', 'g', 'b'])
norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N)
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(dydx)
lc.set_linewidth(2)
line = axs[1].add_collection(lc)
fig.colorbar(line, ax=axs[1])

axs[0].set_xlim(x.min(), x.max())
axs[0].set_ylim(-1.1, 1.1)
plt.show()

最佳答案

不,没有“更简单”的方法。这就是我们在文档中提供该示例的原因。

关于python - 如何轻松地将颜色图应用于线图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58517192/

相关文章:

python - 可插拔应用程序的Django默认设置约定?

python - 你如何接受 Python Bottle 服务器中的任何 URL?

python - 如何防止 matplotlib 窃取焦点?

r - 根据 ggplot 中其他列中的值在 ggplot 中包含垂直线

python - 开始使用plotly时导入报错

python - 删除零行二维 numpy 数组

python - matplotlib 中的历史记录 : Bins are not centered and proportions not correct on the axis

python - Matplotlib事件处理: when do they send matplotlib events and when Qt events

python - Matplotlib: -- 如何在刻度上显示所有数字?

python - 在绘图之前如何将模块转换为列表或数组?