2014-11-04 126 views
0

繼這兩個議題的答案Matplotlib: Plotting numerous disconnected line segments with different colorsmatplotlib: how to change data points color based on some variable一些可變顏色多段,我試圖繪製一組由列表指定段的,比如:繪製基於與matplotlib

data = [(-118, -118), (34.07, 34.16), 
     (-117.99, -118.15), (34.07, 34.16), 
     (-118, -117.98), (34.16, 34.07)] 

和我想要使用基於第二列表的顏色來繪製每個片段,例如:

color_param = [9, 2, 21] 

帶有顏色映射。到目前爲止我使用這條線來顯示細分:

plt.plot(*data) 

我期待的是像

plt.plot(*data, c=color_param, cmap='hot') 

會工作,但事實並非如此。任何人都可以幫我解決這個問題嗎?如果可能,我寧願使用matplotlib。

預先感謝您!

回答

0

你可以考慮以下幾點:

import numpy as np 
import pylab as pl 

# normalize this 
color_param = np.array([9.0, 2.0, 21.0]) 
color_param = (color_param - color_param.min())/(color_param.max() - color_param.min()) 

data = [(-118, -118), (34.07, 34.16), 
     (-117.99, -118.15), (34.07, 34.16), 
     (-118, -117.98), (34.16, 34.07)] 

startD = data[::2] 
stopD = data[1::2] 



for start, stop, col in zip(startD, stopD, color_param): 
    pl.plot(start, stop, color = pl.cm.jet(col)) 

pl.show() 

Rememebr的顏色表pl.cm.hot(0.7)將返回一個顏色值時,你的情況

呈現0和1之間的數字。這是非常方便的,有時,像

編輯:

對於紅色到綠色的顏色表:

import pylab as pl 
import matplotlib.colors as col 
import numpy as np 

cdict = {'red': [(0.0, 1.0, 1.0), 
        (1.0, 0.0, 0.0)], 
     'green': [(0.0, 0.0, 0.0), 
        (1.0, 1.0, 1.0)], 
     'blue': [(0.0, 0.0, 0.0), 
        (1.0, 0.0, 0.0)]} 

my_cmap = col.LinearSegmentedColormap('my_colormap',cdict,256) 


for theta in np.linspace(0, np.pi*2, 30): 
    pl.plot([0,np.cos(theta)], [0,np.sin(theta)], color=my_cmap(theta/(2*np.pi))) 

pl.show() 
+0

這工作完全感謝,有沒有辦法用個人色彩的規模,而不是pl.cm?例如,如果我需要紅色0和綠色​​1,比如設置我自己的色彩地圖。謝謝。 – Antoine 2014-11-04 21:34:31

+0

您可以使用'LinearSegmentedColormap'。有一對夫婦詳盡的教程這裏http://matplotlib.org/api/colors_api.html#matplotlib.colors.LinearSegmentedColormap這裏http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps做這件事。 – ssm 2014-11-05 00:53:05

+0

我已經展示了一個簡單方案的實現。另外,如果這對你有用,你可以考慮接受答案。 :) – ssm 2014-11-05 01:07:45

3

您可以使用LineCollection,這裏有一個例子:

import pylab as pl 
import numpy as np 
from matplotlib.collections import LineCollection 
x = np.linspace(0, 2*np.pi, 100) 
y = np.sin(x) 
c = np.cos(x) 
lines = np.c_[x[:-1], y[:-1], x[1:], y[1:]] 
lc = LineCollection(lines.reshape(-1, 2, 2), array=c, linewidths=3) 
fig, ax = pl.subplots() 
ax.add_collection(lc) 
ax.set_xlim(x.min(), x.max()) 
ax.set_ylim(y.min(), y.max()) 
fig.show() 

Here is the result: