如何在 Matplotlib/Matplotlib 财务图表上添加补丁?

How to add a patch on a Matplotlib/Matplotlib finance chart?

我使用以下方法创建了烛台图表:

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

现在我正在尝试添加一个矩形,该矩形从 x 轴的某个点到 y 位置的 x 轴的另一个点。现在,x 轴上的数据是日期,而 y 轴上的数据是价格。

我尝试了以下方法:

ax1 = axlist[0]

new_patch = Rectangle(xy=(0, 9300), width=0.8, height=0.3, angle=0, color='orange')
ax1.add_patch(new_patch)
ax1.autoscale_view()

有效,问题是我不想使用数字来选择 X 的位置。在 Rectangle(xy=(0, 9300) 中,而不是使用 0,我想使用日期,例如 Rectangle(xy=('2020-06-17 10:30', 9300),但这会引发错误:x 必须是 int

这是我用来绘制图表的数据框示例:

                                   Date     Open     High      Low    Close      Volume
Date
2020-06-17 19:10:00 2020-06-17 19:10:00  9402.02  9411.03  9400.00  9403.59  215.630925
2020-06-17 19:15:00 2020-06-17 19:15:00  9403.59  9412.54  9403.01  9410.57  108.958008
2020-06-17 19:20:00 2020-06-17 19:20:00  9410.16  9413.66  9409.06  9411.88  107.795579

总结一下:我需要在我的图表上绘制一个补丁,我可以使用数字将这个补丁放在 x 轴上,但我想使用日期。有什么办法吗?

编辑:我尝试了建议的解决方案 ,但没有成功:

date = datetime.datetime(2020, 6, 19, 10, 30)
testDate = mdates.date2num(date)
print(testDate)

new_patch = Rectangle(xy=(testDate, 9370), width=1, height=0.3, angle=0, color='orange')
ax1.add_patch(new_patch)
ax1.autoscale_view()

因为它给了我一个荒谬的结果:

不同的库,不同的实现

mplfinance 仅当数据帧使用 DatetimeIndex 时才能生成绘图;这就是为什么必须事先使用 pd.to_datetime 的原因。当您将此图拟合到 matplotlib 图中以对其应用补丁时,matplotlib 无法将 x 值作为日期处理,因为它们没有按日期显示。

它所做的是将它们替换为以 0 开头的整数值列表。这就是为什么当您将补丁的 x 值分配给 testDate 即 737595.4375 时,所有内容都被压缩一次您自动缩放了 x 轴。

解决方案

解决此问题的一种方法是将数据帧 Date 列存储在索引数组中,然后检索匹配日期的索引:

unique_index = pd.Index(df["Date"])
start_x = unique_index.get_loc('2020-06-17 19:10:00')

如果您想在数据框中缺少的日期绘制补丁,则必须找到紧邻起点之前的索引并添加到​​ 0 到 1 之间的任何数字。