2015-11-06 215 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) –