matplotlib:改变线条颜色以捕获数据中的自然时间参数化
我试图改变从两个数组中的数据绘制的线的颜色(例如,matplotlib:改变线条颜色以捕获数据中的自然时间参数化,matplotlib,Matplotlib,我试图改变从两个数组中的数据绘制的线的颜色(例如,ax.plot(x,y))。颜色应随x和y索引的增加而变化。我基本上是试图捕获数组x和y中数据的自然“时间”参数化 在一个完美的世界里,我想要这样的东西: fig = pyplot.figure() ax = fig.add_subplot(111) x = myXdata y = myYdata # length of x and y is 100 ax.plot(x,y,color=[i/100,0,0]) # where i
ax.plot(x,y)
)。颜色应随x
和y
索引的增加而变化。我基本上是试图捕获数组x
和y
中数据的自然“时间”参数化
在一个完美的世界里,我想要这样的东西:
fig = pyplot.figure()
ax = fig.add_subplot(111)
x = myXdata
y = myYdata
# length of x and y is 100
ax.plot(x,y,color=[i/100,0,0]) # where i is the index into x (and y)
产生一条颜色从黑色到深红色再到鲜红色的线条
我已经看到,它可以很好地绘制由某个“时间”数组显式参数化的函数,但我无法让它处理原始数据…第二个示例就是您想要的。。。我对其进行了编辑,以符合您的示例,但更重要的是,阅读我的评论,了解发生了什么:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
x = myXdata
y = myYdata
t = np.linspace(0,1,x.shape[0]) # your "time" variable
# set up a list of (x,y) points
points = np.array([x,y]).transpose().reshape(-1,1,2)
print points.shape # Out: (len(x),1,2)
# set up a list of segments
segs = np.concatenate([points[:-1],points[1:]],axis=1)
print segs.shape # Out: ( len(x)-1, 2, 2 )
# see what we've done here -- we've mapped our (x,y)
# points to an array of segment start/end coordinates.
# segs[i,0,:] == segs[i-1,1,:]
# make the collection of segments
lc = LineCollection(segs, cmap=plt.get_cmap('jet'))
lc.set_array(t) # color the segments by our parameter
# plot the collection
plt.gca().add_collection(lc) # add the collection to the plot
plt.xlim(x.min(), x.max()) # line collections don't auto-scale the plot
plt.ylim(y.min(), y.max())
感谢您指出重塑和连接的情况。这很好。如果您想在线段之间实现更平滑的过渡,可以使用
segs=np.连接([点[:-2],点[1:-1],点[2:],轴=1)
。