【问题标题】:Show last date on x axis for mplfinance chart在 mplfinance 图表的 x 轴上显示最后日期
【发布时间】:2022-01-12 14:36:08
【问题描述】:

我使用 mplfinance lib 创建了一个图表。我想在图表的 x 轴上显示最后一根蜡烛的日期。如何做到这一点?

【问题讨论】:

    标签: python pandas matplotlib mplfinance


    【解决方案1】:

    目前没有直接的方法可以使用 mplfinance 执行此操作(但是正在进行的增强功能会有所帮助;请参阅 issue 428issue 313

    不过,您可以通过以下解决方法来完成这项工作:

    1. 调用mpf.plot()时设置returnfig=True
    2. 从返回的 x 轴获取刻度
    3. 自己格式化刻度(创建刻度标签)
    4. 在末尾多加一个勾号。
    5. 重新设置刻度和刻度标签。

    示例代码:

    给定以下代码和绘图:

    fig, axlist = mpf.plot(df, type='candle',style='yahoo',volume=True,returnfig=True)
    

    我们可以做到以下几点:

    fig, axlist = mpf.plot(df, type='candle',style='yahoo',volume=True,returnfig=True)
    newxticks = []
    newlabels = []
    ##format = '%Y-%b-%d'
    format = '%b-%d'
    
    # copy and format the existing xticks:
    for xt in axlist[0].get_xticks():
        p = int(xt)
        if p >= 0 and p < len(df):
            ts = df.index[p]
            newxticks.append(p)
            newlabels.append(ts.strftime(format))
    
    # Here we create the final tick and tick label:
    newxticks.append(len(df)-1)
    newlabels.append(df.index[len(df)-1].strftime(format))
    
    # set the xticks and labels with the new ticks and labels:
    axlist[0].set_xticks(newxticks)
    axlist[0].set_xticklabels(newlabels)
    
    # now display the plot:
    mpf.show()
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      相关资源
      最近更新 更多