为了概括地说,我正在寻找一种使用 matplotlib 将多个点与 渐变色线 连接起来的方法,但我没有找到它在任何地方。 更具体地说,我正在用单色线绘制 2D 随机游走。但是,由于这些点有一个相关的序列,我想看看这个图,看看数据已经移动到哪里了。一条渐变色的线就可以了。或者是一条透明度逐渐变化的线。
我只是想改进我的数据的可视化。看看这个由 R 的 ggplot2 包生成的美丽图像。我在 matplotlib 中寻找相同的图像。谢谢。
最佳答案
请注意,如果您有很多点,则为每个线段调用 plt.plot
可能会很慢。使用 LineCollection 对象效率更高。
使用 colorline
recipe您可以执行以下操作:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.collections as mcoll
import matplotlib.path as mpath
def colorline(
x, y, z=None, cmap=plt.get_cmap('copper'), norm=plt.Normalize(0.0, 1.0),
linewidth=3, alpha=1.0):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
Plot a colored line with coordinates x and y
Optionally specify colors in the array z
Optionally specify a colormap, a norm function and a line width
"""
# Default colors equally spaced on [0,1]:
if z is None:
z = np.linspace(0.0, 1.0, len(x))
# Special case if a single number:
if not hasattr(z, "__iter__"): # to check for numerical input -- this is a hack
z = np.array([z])
z = np.asarray(z)
segments = make_segments(x, y)
lc = mcoll.LineCollection(segments, array=z, cmap=cmap, norm=norm,
linewidth=linewidth, alpha=alpha)
ax = plt.gca()
ax.add_collection(lc)
return lc
def make_segments(x, y):
"""
Create list of line segments from x and y coordinates, in the correct format
for LineCollection: an array of the form numlines x (points per line) x 2 (x
and y) array
"""
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
return segments
N = 10
np.random.seed(101)
x = np.random.rand(N)
y = np.random.rand(N)
fig, ax = plt.subplots()
path = mpath.Path(np.column_stack([x, y]))
verts = path.interpolated(steps=3).vertices
x, y = verts[:, 0], verts[:, 1]
z = np.linspace(0, 1, len(x))
colorline(x, y, z, cmap=plt.get_cmap('jet'), linewidth=2)
plt.show()
关于python - 如何在 matplotlib 中绘制渐变色线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8500700/