mplfinance plot tiny_layout 切断信息

问题描述

首先必须说,我喜欢 mplfinance,它是在图表上显示数据的一种非常好的方式。

我现在的问题是,我无法减少边框的空间。有一个参数调用“tight_layout”,但它切断了信息。可能我做错了什么。

mpf.plot(df_history,show_nonTrading=True,figratio=(10,7),figscale=1.5,datetime_format='%d.%m.%y',xrotation=90,tight_layout=True,alines=dict(alines=seq_of_points,colors=seq_of_colors,linestyle='-',linewidths=0.5),type='candle',savefig=bildpfad,addplot=apdict,update_width_config=dict(candle_linewidth=0.4))

当我使用 tight_layout=True 时,它看起来像这样:

enter image description here

图表周围的空间很完美,但图表中的数据被截断了。

如果我使用 tight_layout=False 它会占用太多空间并且创建的 html 文件看起来很歪。

enter image description here

有人知道正确的方法吗?

解决方法

您可以采取多种不同的措施来解决此问题。首先,了解发生这种情况的原因。 tight_layout 算法将 x 轴限制设置为刚好超出数据帧日期时间索引的限制,而您的某些 alines 点显然超出此范围。鉴于此,您可以执行以下操作:

  • 使用 kwarg xlim=(xmin,xmax) 手动设置您想要的 x 轴限制。
  • 使用 nan 值填充 ohlc 数据框的末尾,直到您的绘图所需的最新日期。
  • 请求 tight_layout 应将 alines 考虑在内的错误修复或增强。

HTH。


P.S. 目前 xlim 只接受与数据框中的行号(或与 matplotlib 日期相对应,参见下面的 P.P.S.)对应的数字(int 或 float)。我希望尽快增强 xlim 以接受日期。与此同时,尝试这样的事情:

xmin = 0
xmax = len(df_history)*1.4
mpf.plot(df_history,...,xlim=(xmin,xmax))

P.P.S. 我刚刚意识到上述 (xmax = len(df_history)*1.4) 仅适用于 show_nontrading=False。但是,使用 show_nontrading=True 时,您需要以不同方式设置 xmax 和 xmin,如:

import matplotlib.dates as mdates
...

# decide how many days past the end of the data 
# that you want the maximum x-axis limit to be:
numdays = 10
# then:
xmin = mdates.date2num(df_history.index[0].to_py_datetime())
xmax = mdates.date2num(df_history.index[-1].to_py_datetime()) + numdays
mpf.plot(df_history,xmax))

(注意上面它们不是 .index[0],而是 xmax 派生自 .index[-1]


很抱歉,xlim 的上述变通方法过于详尽。这更加激励我完成 xlim 增强,以便用户可以将日期作为字符串或日期时间传递。 mplfinance 的用户不必担心这些日期转换细节。