2016-05-25 85 views
2

我有一个系统有两个变量,vu,它随时间变化。我想绘制他们对彼此,并有颜色指示的时间。Matplotlib:每个日期的不同颜色,通过颜色条标记

这里是我的数据,其中使用pd.to_datetime()生成索引:

   v   u 
date      
2001-01-01 3.9 4.290910 
2002-01-01 2.8 5.807681 
2003-01-01 2.8 5.956179 
2004-01-01 2.6 5.771250 
2005-01-01 2.7 5.335874 
2006-01-01 3.1 4.792693 
2007-01-01 3.3 4.576049 
2008-01-01 3.0 5.008100 
2009-01-01 2.0 8.392731 
2010-01-01 2.0 9.961898 
2011-01-01 2.2 9.168686 
2012-01-01 2.7 8.360966 
2013-01-01 2.7 7.805654 
2014-01-01 2.7 6.742811 
2001-04-01 3.6 4.474629 
2002-04-01 2.6 5.899864 
2003-04-01 2.5 6.209195 
2004-04-01 2.7 5.644648 
2005-04-01 3.1 5.170083 

我试图

fig, ax = plt.subplots() 
smap = ax.scatter(df['v'],df['u'],s=500,c=df.index, 
        edgecolors='none', marker='o', cmap=cmap)) 

cb = fig.colorbar(smap, orientation='vertical') 

cb.ax.set_yticklabels(df.index.strftime('%b %Y')) 

但是,它错误地将现在从2001 - 2003年的日期范围,而不是2001年-2014:

smaple image

+0

在matplotlib邮件列表遇到了这个。 http://matplotlib.1069221.n5.nabble.com/colorbar-with-date-time-formatting-td16553.html – dagrha

+0

@dagrha我也发现,但它给了我'溢出错误:有符号整数大于最大'。然后我发现https://github.com/patwmcnamara/GADS11-NYC-Summer2014/issues/50,它建议按我在这里做的方式做。 – FooBar

+0

我通过在cb.axis上设置'yticklabels'之前在颜色条上设置了'cb.set_ticks(df.index)'来实现它。请注意,我必须按日期对df进行排序,然后reset_index(),以便索引是整数而不是日期时间。 – dagrha

回答

1

您创建indices然后你不使用它。

你必须使用它my_colors

cmap = plt.get_cmap('viridis') 
indices = np.linspace(0, cmap.N, len(df)) 
my_colors = [cmap(int(i)) for i in indices] 

fig, ax = plt.subplots() 
for i, idx in enumerate(df.index): 
    ax.plot(df.loc[idx, 'u'], df.loc[idx, 'v'], '.', color=my_colors[i]) 
相关问题