Scatterplot of two Pandas Series, coloured by date and with legend
<p>I am studying financial time series, in the format of pandas series. To compare two series I do a scatterplot, and to visualise the time evolution in the scatterplot I can colour them. This is all fine.</p>

<p>My question relates to the legend showing the colours.
I would like the legend to show the date/year that the colour corresponds to, rather than just an the index of the data entry, as now. But I haven't been able to do this, or to find a question like this on stackoverflow.</p>

<p>I know the time series knows the dates, and if you just plot a time series, the x-axis will show the dates.</p>

<p>My code is</p>

<pre><code>from pandas_datareader import data as web
import matplotlib.pyplot as plt
import pandas as pd

#Download data
start = '2010-1-1'
end = '2016-10-1'
AAPL = web.DataReader('AAPL', 'yahoo', start=start, end=end)['Adj Close']
TSLA = web.DataReader('GOOG', 'yahoo', start=start, end=end)['Adj Close']

#Scatterplot
plt.scatter(AAPL, TSLA, alpha=.4, c=range(len(AAPL)))
plt.colorbar()
plt.xlabel("AAPL")
plt.ylabel("TSLA")
plt.grid()
plt.show()
</code></pre>

<p>This code produces this plot:
<a href="https://i.stack.imgur.com/KjU2w.png" rel="nofollow">Scatterplot with colours and legend</a></p>

<p>Thanks</p>

<p>While there might be an easier answer out there (anyone?), to me the most straightforward way is to change the colorbar ticks manually. </p>

<p>Try the following before you invoke <code>plt.show()</code>:</p>

<pre><code>clb = plt.gci().colorbar # get the colorbar artist
# get the old tick labels (index numbers of the dataframes)
clb_ticks = [int(t.get_text()) for t in clb.ax.yaxis.get_ticklabels()]
# convert the old, index, ticks into year-month-day format
new_ticks = AAPL.index[clb_ticks].strftime("%Y-%m-%d")
clb.ax.yaxis.set_ticklabels(new_ticks)
</code></pre>

<p>Note that <code>strftime</code> does not appear to be implemented in <code>pandas</code> versions older than <code>0.18</code>. In that case you'll have to replace <code>.strftime("%Y-%m-%d")</code> with <code>.apply(lambda x: x.strftime('%Y-%m-%d'))</code> as explained <a href="http://stackoverflow.com/questions/19738169/convert-column-of-date-objects-in-pandas-dataframe-to-strings">here</a>.</p>

<p><a href="https://i.stack.imgur.com/v6cPs.png" rel="nofollow"><img src="https://i.stack.imgur.com/v6cPs.png" alt="clb-ymd_labels-pandas"></a></p>

python pandas matplotlib legend series