Plotly Dash如何将垂直柱状图tooltip设置为柱顶显示而非右侧
需求说明
- 目标:将垂直柱状图的悬浮提示框(tooltip)从默认的柱体右侧位置,调整为显示在垂直柱体的顶部
- 参考效果:

- 已尝试操作:查阅Plotly柱状图官方文档、参考公开开发教程,未找到对应实现方案
现有实现代码
数据集与柱状图绘制逻辑
import pandas as pd import plotly.express as px df = pd.DataFrame({ "Day": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"], "Amount": [4, 1, 2, 2, 4, 5,8], }) fig = px.bar(df, x="Day", y="Amount",orientation="v",opacity=0.9,barmode='relative',color_discrete_sequence=["purple"],text='Day',template='none') fig.update_traces(texttemplate = '%{text:.2s}',textposition = 'outside',width = [.3,.3,.3,.3,.3,.3,.3])
Dash页面嵌入代码
from dash import html, dcc html.Div(className="bar-chart",children=[ html.H1('Weekly Statistics'), dcc.Dropdown( ['Last Week', 'Last Month', 'Last Year'], 'Montreal', clearable=False, style={ 'outline':'none', 'text-decoration':'none', 'width':'32vw', 'margin-top':'10px', 'margin-right':'20px', 'color':'#28285F', 'text-align':'right' } ), dcc.Graph( style = { 'display':'flex', 'flex-direction':'column', 'align-items':'flex-start', 'position':'absolute', 'width':'40vw', 'height':'20vw', 'margin-left':'5vw', 'margin-top':'6vw', 'background':'rgba(85, 190, 155, 0.1)' }, id='example-graph', figure=fig ), ]),
实现方案
直接在柱状图的update_traces配置中新增hoverlabel位置参数即可,无需修改Dash层布局代码,修改后的配置如下:
fig.update_traces( texttemplate = '%{text:.2s}', textposition = 'outside', width = [.3,.3,.3,.3,.3,.3,.3], # 新增配置将tooltip固定在柱体顶部 hoverlabel=dict( position="top" ) )
参数说明
hoverlabel.position是Plotly原生支持的提示框位置配置项,垂直柱状图场景下可选值:right:默认值,提示框显示在柱体右侧top:提示框显示在柱体顶部,即目标效果bottom:提示框显示在柱体底部
- 如果需要调整提示框和柱顶的间距,可以搭配
fig.update_layout(hoverdistance=10)调整悬浮触发距离,数值越大触发时提示框离柱体越远 - 也可以在
hoverlabel字典中新增bgcolor、font_size、bordercolor等参数,自定义提示框样式匹配页面设计风格
内容的提问来源于stack exchange,提问作者Amandeep Singh
相关产品推荐
相关产品推荐

