2016-07-05 46 views
0

我需要此帮助。 情节是好的,但当我徘徊在点时,我得到了S的价格作为Y(这是正确的),而不是日期为X我得到一个时间戳。 有没有人能够解决它?谢谢!使用mpld3绘制日期标签

import matplotlib.pyplot as plt 
import mpld3 
from mpld3 import plugins 
import pandas.io.data as pdweb 
import datetime 
mpld3.enable_notebook() 
%matplotlib inline 


price = pdweb.get_data_yahoo("^GSPC",start = datetime.datetime(2014,1,1),end=datetime.datetime(2016,6,30))['Adj Close'] 
fig, ax = plt.subplots(figsize=(12,8)) 
ax.plot(price.index, price, lw=1) 
points = ax.scatter(price.index, price, alpha=0.1) 
plugins.connect(fig, plugins.LineLabelTooltip(points)) 

回答

1

这可能不是最好的方法,但它的工作原理:

series = ax.plot(price) 
date_axis = [pd.to_datetime(str(date)).strftime('%Y.%m.%d') for date in series[0].get_data()[0]] 
labels = [(date, " {0}".format(val)) for date, val in zip(date_axis, series[0].get_data()[1])] 

所以在步骤使其比上面的混乱更清晰一点:

1)地块价格系列

series = ax.plot(price) 

2)将datatime64(该系列的x轴)的numpy.ndArray中的每个日期取为一个字符串。

string_dates = [str(date) for date in series[0].get_data()[0]] 

3)然后将字符串转换为pandas datetime。

dates = [pd_to_datetime(date) for date in string_dates] 

4)然后使用的strftime()格式化每个日期字符串,并将其保存到date_axis

date_axis = [date.strftime('%Y.%m.%d') for date in dates] 

就像我说的,这是几乎可以肯定不是这样做的有效方式,但它的工作对于我来说,暂时的解决办法是试图找出一段时间。在SO上找到这个地方,没有链接到手。

+0

非常感谢,但我得到这个错误..任何想法如何解决它?再次感谢 – MrFed

+0

AttributeError:'str'对象没有属性'strftime' – MrFed