Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: Different colors for each date, labelled via colorbar

I have a system in two variables, v and u, which change over time. I would like to plot them against each other, and have the time indicated by the color.

Here is my data, where the index was generated using 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

I tried

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'))

However, it falsely now sets the date range from 2001-2003, instead of 2001-2014:

smaple image

like image 368
FooBar Avatar asked Sep 18 '25 20:09

FooBar


1 Answers

You create indices and then you do not use it.

You have to use it for 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])
like image 55
LouisBBBB Avatar answered Sep 20 '25 15:09

LouisBBBB