我有一个包含两个变量的系统,v 和 u,它们随时间变化。我想将它们相互绘制,并用颜色指示时间。
这是我的数据,其中索引是使用 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:
请您参考如下方法:
您创建索引,然后您不使用它。
你必须将它用于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])
