如何为Plotly子图中的蜡烛图(Candlestick)添加标注?
问题:Plotly子图中蜡烛图标注不生效的原因及解决办法
你当前的标注代码无效,核心问题有两个:
- 未指定标注所属的子图位置:在多子图场景下,
add_annotation默认会把标注添加到最后一个子图(也就是你的成交量柱图所在的第2行),但你需要给第1行的蜡烛图加标注,必须显式指定row=1, col=1参数。 - y值传入错误:
y=df["Close"]传入的是整个收盘价序列,标注需要单个具体数值,你得指定对应位置的收盘价,比如用df["Close"].iloc[i];同时如果你的索引不是连续整数,x=i建议改成df.index[i]来精准定位x轴位置。
修正后的标注代码示例
假设你要在第i个数据点位置添加标注,代码应修改为:
# 替换i为你需要标注的具体索引位置(比如i=10) fig.add_annotation( x=df.index[i], y=df["Close"].iloc[i], text="Test text", showarrow=True, arrowhead=1, row=1, # 指定标注在蜡烛图所在的第1行子图 col=1 # 指定标注在第1列子图 )
完整可运行代码示例
将标注代码插入到蜡烛图trace之后即可:
# Plot chart # Create subplots and mention plot grid size fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_width=[0.2, 0.7]) # Plot OHLC on 1st row fig.add_trace(go.Candlestick(x=df.index, open=df["Open"], high=df["High"], low=df["Low"], close=df["Close"], name="OHLC"), row=1, col=1 ) # 添加标注到蜡烛图子图 i = 10 # 替换为目标标注位置的索引 fig.add_annotation( x=df.index[i], y=df["Close"].iloc[i], text="Test text", showarrow=True, arrowhead=1, row=1, col=1 ) # Bar trace for volumes on 2nd row without legend fig.add_trace(go.Bar(x=df.index, y=df['Volume'], showlegend=False), row=2, col=1) fig.update_layout(xaxis_rangeslider_visible=False, title_text=f'{ticker}') fig.write_html(fr"E:\Documents\PycharmProjects\xxxxxxxx.html")
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

