You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly图表Tooltip自定义需求:延长显示时长或点击永久展示

实现Plotly图表Tooltip的自定义时长与点击永久展示

一、自定义Tooltip悬停消失时长(CSS快速方案)

Plotly图表本身没有内置的tooltip时长配置项,但可以通过CSS修改tooltip的过渡延迟,实现鼠标移开后延迟消失的效果。直接在Dash应用中注入样式即可:

/* 修改Plotly tooltip的消失延迟 */
.js-plotly-plot .plotly .hoverlayer .tooltip {
  transition-delay: 3s !important; /* 鼠标离开后3秒才消失,可自行调整数值 */
  transition-duration: 0.2s !important; /* 显示/隐藏的过渡动画时长 */
}

在Dash里可以通过html.Style组件把这段CSS注入到页面中,无需额外的CSS文件。


二、点击数据点永久展示带链接的Tooltip(Dash回调方案)

原生Plotly tooltip无法实现点击后永久展示并添加可点击链接,这里可以用Dash的事件回调+自定义HTML容器来模拟:

完整示例代码

import dash
from dash import dcc, html, Input, Output, State
import plotly.express as px

app = dash.Dash(__name__)

# 示例数据集
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")

app.layout = html.Div([
    dcc.Graph(id='scatter-plot', figure=fig),
    # 自定义Tooltip容器,默认隐藏
    html.Div(
        id='custom-tooltip',
        style={
            'position': 'absolute',
            'background': '#fff',
            'padding': '8px 12px',
            'border': '1px solid #ddd',
            'borderRadius': '4px',
            'boxShadow': '0 2px 6px rgba(0,0,0,0.15)',
            'display': 'none',
            'zIndex': 9999,
            'pointerEvents': 'auto'  # 确保链接可点击
        }
    ),
    # 可选:添加之前的悬停延迟CSS
    html.Style("""
        .js-plotly-plot .plotly .hoverlayer .tooltip {
          transition-delay: 2s !important;
        }
    """)
])

@app.callback(
    [Output('custom-tooltip', 'children'),
     Output('custom-tooltip', 'style')],
    Input('scatter-plot', 'clickData'),
    State('custom-tooltip', 'style')
)
def update_custom_tooltip(click_data, current_style):
    if not click_data:
        # 未点击数据点时隐藏容器
        return '', {'display': 'none', **current_style}
    
    # 提取点击点的详细数据
    point = click_data['points'][0]
    species = point['customdata'][0]
    x = point['x']
    y = point['y']
    
    # 生成带可点击链接的Tooltip内容
    tooltip_content = html.Div([
        html.P(f"种类: {species}"),
        html.P(f"花萼宽度: {x}"),
        html.P(f"花萼长度: {y}"),
        html.A("查看该物种详情", href="https://example.com", target="_blank")
    ])
    
    # 定位Tooltip到点击位置附近(用client坐标适配响应式图表)
    new_style = {
        'display': 'block',
        'left': f'{point["clientX"] + 15}px',
        'top': f'{point["clientY"] + 15}px',
        **current_style
    }
    
    return tooltip_content, new_style

if __name__ == '__main__':
    app.run_server(debug=True)

方案说明

  1. 用一个绝对定位的html.Div作为自定义Tooltip容器,初始隐藏;
  2. 监听图表的clickData事件,触发回调更新容器内容与显示状态;
  3. 通过点击事件中的clientX/clientY坐标定位Tooltip,适配响应式图表;
  4. 容器内可以添加任意HTML元素(包括链接),完全自定义内容。

内容的提问来源于stack exchange,提问作者phobic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:25:14