两个Pandas系列的散点图,按日期和图例

时间:2016-10-15 16:27:49

标签: python pandas matplotlib legend series

我正在以熊猫系列的形式学习金融时间序列。为了比较两个系列,我做了一个散点图,为了可视化散点图中的时间演变,我可以给它们着色。这一切都很好。

我的问题与显示颜色的图例有关。 我希望图例显示颜色对应的日期/年份,而不仅仅是数据条目的索引,就像现在一样。但是我无法做到这一点,或者在stackoverflow上找到这样的问题。

我知道时间序列知道日期,如果您只绘制时间序列,x轴将显示日期。

我的代码是

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

此代码生成此图: Scatterplot with colours and legend

由于

1 个答案:

答案 0 :(得分:1)

虽然可能有一个更简单的答案(任何人?),对我来说,最直接的方法是手动更改颜色栏刻度。

在调用plt.show()之前尝试以下操作:

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)

请注意,strftime似乎并未在早于pandas的{​​{1}}版本中实施。在这种情况下,您必须按here解释0.18替换.strftime("%Y-%m-%d")

clb-ymd_labels-pandas