2015-11-06 210 views
0

我有一個有三列Date(時間戳),Color('紅'或'藍')和Value(int)的熊貓數據框。seaborn或matplotlib折線圖,線顏色取決於變量

我目前得到一個線圖,從它與下面的代碼:

import matplotlib.pyplot as plt 
import pandas as pd 
Dates=['01/01/2014','02/01/2014','03/01/2014','04/01/2014','05/01/2014','06/01/2014','07/01/2014'] 
Values=[3,4,6,5,4,5,4] 
Colors=['red','red','blue','blue','blue','red','red'] 
df=pd.DataFrame({'Dates':Dates,'Values':Values,'Colors':Colors}) 
df['Dates']=pd.to_datetime(df['Dates'],dayfirst=True) 

grouped = df.groupby('Colors') 
fig, ax = plt.subplots() 

for key, group in grouped: 
    group.plot(ax=ax, x="Dates", y="Values", label=key, color=key) 

plt.show() 

我想的線條顏色依賴於「色」列。我怎樣才能做到這一點?

我看過here散點圖的一個類似的問題,但似乎我不能將相同的解決方案應用於時間序列折線圖。目前

我的輸出是這樣的:

enter image description here

我想正如我說你能達到這樣的(只有一條線,但幾種顏色)

enter image description here

+0

可能的複製[繪製不同的顏色使用matplotlib不同的分類級別(http://stackoverflow.com/questions/26139423/plot-different- color-for-different-categorical-levels-using-matplotlib) –

+0

你可以附加你的數據框的一部分嗎? –

+0

剛剛添加它:-) –

回答

1

link找到答案我附上評論:

import matplotlib.pyplot as plt 
import pandas as pd 
Dates=['01/01/2014','02/01/2014','03/01/2014','03/01/2014','04/01/2014','05/01/2014'] 
Values=[3,4,6, 6,5,4] 
Colors=['red','red', 'red', 'blue','blue','blue'] 
df=pd.DataFrame({'Dates':Dates,'Values':Values,'Colors':Colors}) 
df['Dates']=pd.to_datetime(df['Dates'],dayfirst=True) 

grouped = df.groupby('Colors') 
fig, ax = plt.subplots(1) 

for key, group in grouped: 
    group.plot(ax=ax, x="Dates", y="Values", label=key, color=key) 

當變色,你需要添加額外的點,使線​​連續

+0

謝謝。這是我不清楚的一部分。這種解決方案將每種顏色分成不同的線條,當顏色不隨時間重複時,效果很好。當他們這樣做時,相同顏色的線段連接,因此兩條線出現在同一日期。我認爲matplotlib只允許每行一種顏色?以下是Tableau中我試圖實現的一個示例:http://1.bp.blogspot.com/-ZuCBGy0rYwU/T_xIBulGULI/AAAAAAAAEko/QRKpPpGyQXs/s1600/Differential+(3).png –

+0

如果您願意,可以這樣做當顏色改變時會重複點,我修改了該答案 –

+0

您也可以嘗試下面的一個:[multicolored_line](http://matplotlib.org/examples/pylab_examples/multicolored_line.html) –