【问题标题】:Plotting date labels with mpld3使用 mpld3 绘制日期标签
【发布时间】:2016-07-05 13:50:34
【问题描述】:

我需要这方面的帮助。 情节很好,但是当我将鼠标悬停在这些点上时,我得到的标准普尔价格为 y(这是正确的),而不是日期为 x 我得到一个时间戳。 有没有人能够修复它?谢谢!

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

【问题讨论】:

    标签: python datetime mpld3


    【解决方案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 的 numpy.ndArray 中的每个日期(系列的 x 轴)设为字符串。

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

    3) 然后将字符串转换为 pandas 日期时间。

    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 的其他地方找到了这个,手头没有链接。

    【讨论】:

    • 非常感谢,但我收到了这个错误。知道如何解决吗?再次感谢
    • AttributeError: 'str' 对象没有属性 'strftime'
    猜你喜欢
    • 2021-09-12
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    相关资源
    最近更新 更多