You need to enable JavaScript to run this app. 使用mplfinance外部轴方法绘制多蜡烛图时如何嵌入成交量
优惠活动
大模型
产品
解决方案
定价
更多

使用mplfinance外部轴方法绘制多蜡烛图时如何嵌入成交量

mplfinance 多画布批量蜡烛图成交量嵌入实现方案

场景基础

  • 项目需求为基于mplfinance库在同一画布内批量绘制300张以上蜡烛图,经调研确认,该规模的批量绘图场景仅可通过外部轴绘图模式实现,该模式灵活性更强,理论上支持无上限数量的图表渲染。

初始实现的布局问题

最初采用add_subplot方法创建轴对象,可运行的实现代码如下:

import mplfinance as mpf

s = mpf.make_mpf_style(base_mpf_style='yahoo', rc={'font.size': 6})
fig = mpf.figure(figsize=(34, 13.2), style=s, tight_layout=True)

ax_p = fig.add_subplot(n_rows, n_cols, pos_price)
ax_v = fig.add_subplot(n_rows, n_cols, pos_vol, sharex=ax_p)

fig, ax_list = mpf.plot(resampled_df, type='candle', ax=ax_p, volume=ax_v, show_nontrading=False,
                     datetime_format='%a %d-%m-%y', xrotation=0, returnfig=True)

上述代码已可成功批量生成数百张蜡烛图,但存在明显布局缺陷:成交量被绘制为完全独立的子图,排布在蜡烛图下方,无法嵌入对应蜡烛图的所属绘图区域内。

此前查阅mplfinance官方文档issue114的相关参考说明,内容对库的新手用户友好度较低,没有给出可直接落地的操作路径,难以快速实现嵌入效果。

最终落地效果实现

经调试验证,将子图创建方式从add_subplot替换为add_axes,即可实现多图场景下成交量嵌入蜡烛图底部的理想效果,调整后的可运行代码片段如下:

ax_intra_day_candle = fig.add_axes([x_pos, y_pos, ax_width, ax_height])
ax_intra_day_candle.set_title(title)
ax_intra_day_volume = fig.add_axes([x_pos, y_pos - ax_vol_height, ax_width, ax_vol_height], sharex=ax_intra_day_candle)
mpf.plot(intra_day_df, type='candle', ax=ax_intra_day_candle, volume=ax_intra_day_volume, show_nontrading=False,
                 datetime_format='%a %m-%d', xrotation=0)

内容的提问来源于stack exchange,提问作者data2wealth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.04 03:15:06