2012-04-20 42 views
9

我想改變從兩個數組(例如,ax.plot(x,y))中的數據繪製的線的顏色。顏色應該隨着xy的指數增加而變化。我基本上試圖捕獲數組xy中數據的自然「時間」參數化。matplotlib:不同顏色的線捕捉數據中的自然時間參數化

在一個完美的世界,我想是這樣的:

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) 

產生顏色從黑色變到暗紅色和成亮紅色的線。

我看到examples,對於策劃一些「時間」陣列明確參數的函數工作得很好,但我不能讓它使用原始數據工作...

回答

10

第二個例子是一個你想...我已經編輯它適合你的榜樣,但更重要的是看我的意見,瞭解正在發生的事情:

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()) 
+0

謝謝你指出什麼是與改造並串連發生。這很好。 – 2012-04-21 02:01:15

+0

如果您想在線段之間進行平滑過渡,您可以改爲'segs = np.concatenate([points [: - 2],points [1:-1],points [2:]],axis = 1)''。 – shockburner 2017-10-20 17:58:56