Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何轻松地将颜色贴图应用于线图?_Python_Matplotlib_Plot_Colormap - Fatal编程技术网

Python 如何轻松地将颜色贴图应用于线图?

Python 如何轻松地将颜色贴图应用于线图?,python,matplotlib,plot,colormap,Python,Matplotlib,Plot,Colormap,我发现了生成这些图的示例: 那里的代码使用了x,y值的LineCollection的重塑d串联,这看起来相当麻烦。有没有更简单的方法将颜色贴图应用于线条图?类似于绘图(x,y,cmap='viridis',colors=dxdy)?为了澄清,我不是在询问如何使用colormap设置多行的恒定颜色(如所述),而是在非恒定颜色的单行上应用colormap 为了完整起见,下面是该示例中的代码: import numpy as np import matplotlib.pyplot as plt f

我发现了生成这些图的示例:

那里的代码使用了
x,y
值的
LineCollection
重塑
d串联,这看起来相当麻烦。有没有更简单的方法将颜色贴图应用于线条图?类似于
绘图(x,y,cmap='viridis',colors=dxdy)
?为了澄清,我不是在询问如何使用colormap设置多行的恒定颜色(如所述),而是在非恒定颜色的单行上应用colormap


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

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()
不,没有“更简单”的方法。这就是为什么我们在文档中有这个例子