Plotly共享X轴子图:实现Hover同时显示两个子图Y值
解决Plotly共享X轴子图悬停时同时显示所有Y值的问题
你的问题核心是悬停模式没有正确合并两个子图的Y值数据,主要有两个原因:一是代码里加了不必要的stackgroup='one',二是默认的hovermode="x unified"在X轴数据不完全匹配时无法正常生效。下面是具体的修复方案:
关键修改点
- 移除两个
go.Scatter里的stackgroup='one':堆叠组会让Plotly把数据按组处理,干扰悬停数据的合并。 - 确保两个数据集的X轴(日期)完全对齐:如果A_error和B_error的CloseDate有差异,用pandas合并数据集,保证每个日期都有对应的A、B价格值(缺失值填NaN不影响绘图)。
- 保留
hovermode="x unified",这个参数是让同一X值下的所有数据都显示在悬停框里的关键。
修改后的完整代码
import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots title = 'Price over time' err = 'Price' # 合并两个数据集,确保X轴日期完全对齐 merged_df = pd.merge(A_error[['CloseDate', err]], B_error[['CloseDate', err]], on='CloseDate', how='outer', suffixes=('_A', '_B')) fig = make_subplots(rows=2, cols=1, vertical_spacing=0.05, shared_xaxes=True, subplot_titles=(title, "")) # A子图:使用合并后的数据 fig.add_trace(go.Scatter(x=merged_df['CloseDate'], y=merged_df[f'{err}_A'], line_color='green', marker_color='green', mode='lines+markers', showlegend=True, name="A"), row=1, col=1, secondary_y=False) # B子图:使用合并后的数据 fig.add_trace(go.Scatter(x=merged_df['CloseDate'], y=merged_df[f'{err}_B'], line_color='blue', mode='lines+markers', showlegend=True, name="B"), row=2, col=1, secondary_y=False) fig.update_yaxes(tickprefix='$') fig.add_hline(y=0, line_width=3, line_dash="dash", line_color="black") fig.update_layout(#height=600, width=1400, hovermode="x unified", legend_traceorder="normal")
额外说明
如果你的A_error和B_error日期本来就完全一致,那可以跳过合并步骤,直接移除stackgroup就能解决问题。合并数据是为了兼容日期不完全匹配的场景,保证悬停时每个日期都能同时显示A和B的数值(哪怕其中一个是NaN,悬停框里也会显示对应的名称和空值)。
内容的提问来源于stack exchange,提问作者user9532692
相关产品推荐
相关产品推荐

