如何固定Plotly Express中hover template悬浮提示框的位置
实现方案
针对你提到的x unified模式悬浮提示固定位置的需求,Plotly 原生没有提供直接修改默认提示定位的配置项,可通过「隐藏原生跟随鼠标的提示框 + 添加固定位置的自定义提示容器 + 绑定悬停事件实时更新内容」的方式实现,提示内容会随鼠标悬停位置实时刷新,交互逻辑和原生效果完全一致。
基础示例(固定在图表右下角)
以下是可直接运行的实现代码:
import plotly.express as px # 加载示例数据 df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", color="country") # 配置悬停模式为x轴统一采集,同时隐藏原生跟随鼠标的提示框 fig.update_layout( hovermode="x unified", hoverlabel=dict( bgcolor="rgba(0,0,0,0)", bordercolor="rgba(0,0,0,0)", font=dict(color="rgba(0,0,0,0)") ) ) # 在右下角添加固定位置的提示容器,使用paper相对坐标系,不受轴范围影响 fig.add_annotation( xref="paper", yref="paper", x=0.98, y=0.02, xanchor="right", yanchor="bottom", align="left", showarrow=False, bgcolor="white", bordercolor="#cccccc", borderwidth=1, borderpad=8, text="悬停图表查看对应数据", name="fixed_hover_tip" ) # 绑定悬停回调,实时更新固定提示框的内容 def update_tip_content(trace, points, state): if not points.point_inds: return current_x = points.xs[0] tip_text = f"<b>{fig.layout.xaxis.title.text}: {current_x}</b><br>" # 遍历所有序列,采集当前x位置对应的数值 for data_trace in fig.data: match_index = list(data_trace.x).index(current_x) current_y = data_trace.y[match_index] tip_text += f"<span style='color:{data_trace.line.color}'>●</span> {data_trace.name}: {round(current_y, 2)}<br>" # 更新提示框内容 fig.update_annotations(selector=dict(name="fixed_hover_tip"), text=tip_text) # 为所有图形序列绑定悬停事件 for trace in fig.data: trace.on_hover(update_tip_content) fig.show()
自定义调整说明
- 位置修改:调整注释的
x、y参数即可修改提示框位置,paper坐标系取值范围为0-1:x=0为图表最左侧、x=1为最右侧,y=0为图表最底部、y=1为最顶部。比如要放到右上角,设置x=0.98, y=0.98, xanchor="right", yanchor="top"即可。 - 样式修改:可自行调整注释的
bgcolor、bordercolor、font属性,和原生提示样式保持统一。 - Dash场景适配:如果是在Dash应用中使用,无需绑定前端悬停事件,直接将图表组件的
hoverData属性作为回调输入,更新页面上固定定位的html.Div提示组件内容即可,实现逻辑更简单。

内容的提问来源于stack exchange,提问作者mohammad farhady
相关产品推荐
相关产品推荐

