mplfinance如何设置vlines位于candlesticks下方并延伸至图表顶边
mplfinance vlines层级与高度问题解决方案
问题1:vlines覆盖K线,调整至K线下层
mplfinance内置vlines参数未开放图层层级配置,默认绘制层级高于K线,因此会出现遮挡。
解决方式:不在mpf.plot()中传入vlines参数,在拿到返回的坐标轴对象后手动绘制竖线,设置zorder=1即可将竖线压在K线下方(K线默认zorder为2),即使调高alpha值也不会影响K线可读性。
问题2:vlines未贴合图表顶部边缘
内置vlines默认基于数据坐标绘制,会自动预留轴边距,因此顶部存在空隙。
解决方式:手动绘制vlines时,将y轴坐标系切换为轴相对坐标系,设置ymin=0、ymax=1,配合*transform=ax.get_xaxis_transform()*参数,即可让竖线从轴最底部完全延伸至最顶部,消除边缘空隙。
修改后可直接运行的代码
# 提前提取盘前盘后交易时段对应的时间点 pre_post_times = df.between_time('16:00', '09:30').index.tolist() fig, axlist = mpf.plot(df, type='candle', volume=True, ylabel='', ylabel_lower='\n<thousands>', returnfig=True, style=style, figratio=(21, 9), warn_too_much_data=970, addplot=vwap, hlines=dict(hlines=previousCloseLine(), colors='white', linestyle='dashed'), # 移除原代码中的vlines传参 datetime_format='%H:%M', tight_layout=True ) # 主价格轴手动绘制竖线 main_ax = axlist[0] main_ax.vlines( x=pre_post_times, ymin=0, ymax=1, colors='#323538', linewidths=1, alpha=0.5, zorder=1, transform=main_ax.get_xaxis_transform() ) # 如果需要成交量副图也显示相同阴影,添加以下代码即可 vol_ax = axlist[1] vol_ax.vlines( x=pre_post_times, ymin=0, ymax=1, colors='#323538', linewidths=1, alpha=0.5, zorder=1, transform=vol_ax.get_xaxis_transform() )
原问题实现效果参考:
内容的提问来源于stack exchange,提问作者André Fael
相关产品推荐
相关产品推荐


