You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用matplotlib与mplfinance绘制K线图后添加标记致图消失求助

问题原因及解决办法

问题原因

  • mplfinance绘制K线时,会自动将DataFrame的datetime索引转换为连续的数值坐标(从0开始递增),而非直接使用datetime对象作为x轴坐标。
  • 直接调用ax2.plot(dates, prices, 'o')传入原始datetime对象时,matplotlib会将x轴切换为datetime坐标系统,此时K线的数值坐标不在新轴的范围内,导致K线被隐藏,同时X轴因坐标系统冲突显示异常。

解决办法

方法一:手动转换订单日期为mplfinance数值坐标

  1. 确保stock.data的索引为datetime类型(mplfinance的要求)。
  2. 为每个订单日期找到其在stock.data索引中的对应位置(即数值x坐标)。
fig, (ax1, ax2) = plt.subplots(2)

# 绘制K线图
mpf.plot(stock.data, ax=ax2, type='candle')
ax2.set_title(f'Stock History of {stock.symbol}')
ax2.set_xlabel('Date')
ax2.set_ylabel('Price')

# 处理订单标记:转换日期为匹配的数值坐标
x_coords = []
prices = []
for key, order in broker.orders.items():
    # 检查订单日期是否在股票数据索引中
    if order.date in stock.data.index:
        idx = stock.data.index.get_loc(order.date)
        x_coords.append(idx)
        prices.append(order.price)

# 绘制交易点位标记
ax2.plot(x_coords, prices, 'ro', markersize=8)

plt.tight_layout()
plt.show()

方法二:使用mplfinance原生addplot添加标记

mplfinance提供了原生API添加额外绘图元素,无需手动处理坐标转换,兼容性更好:

import pandas as pd

# 将订单数据整理为DataFrame,索引设为datetime
order_df = pd.DataFrame({
    'price': [order.price for order in broker.orders.values()]
}, index=[order.date for order in broker.orders.values()])

# 创建mplfinance绘图对象
ap = mpf.make_addplot(order_df['price'], type='scatter', marker='o', color='red', markersize=8)

# 绘制子图
fig, (ax1, ax2) = plt.subplots(2)

# 绘制交易订单到ax1
ax1.plot(...)

# 同时绘制K线和交易标记到ax2
mpf.plot(stock.data, ax=ax2, type='candle', addplot=ap)
ax2.set_title(f'Stock History of {stock.symbol}')
ax2.set_xlabel('Date')
ax2.set_ylabel('Price')

plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:33:31