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

Plotly Python中能否为布局图片触发悬停事件?

在Plotly Python中为布局图片添加悬停事件的方案

核心结论

Plotly Python原生的Figure对象中,通过add_layout_image添加的布局图片没有直接的on_hover绑定方法,你尝试的my_image = fig.data[layout_image]写法也存在错误——布局图片存储在fig.layout.images而非fig.data中,且布局层元素不支持像Scatter这类trace那样的悬停事件API。

可行解决方案:使用Dash实现

要实现布局图片的悬停检测,需要借助Dash框架,通过监听图表的hover事件,判断鼠标坐标是否落在图片的坐标范围内,从而触发对应逻辑。

完整代码示例

import dash
from dash import dcc, html, Input, Output, State
import plotly.graph_objects as go

# 创建Dash应用
app = dash.Dash(__name__)

# 定义图表及布局图片参数
fig = go.Figure()
fig.add_trace(go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1]))

# 存储图片的坐标参数,用于后续判断悬停范围
image_params = dict(
    source="https://images.plot.ly/language-icons/api-home/python-logo.png",
    xref="x",
    yref="y",
    x=0,
    y=3,
    sizex=2,
    sizey=2,
    sizing="stretch",
    opacity=0.5,
    layer="below"
)
fig.add_layout_image(image_params)

# 应用布局
app.layout = html.Div([
    dcc.Graph(id='hover-image-graph', figure=fig),
    html.Div(id='hover-output', style={'margin-top': 20})
])

# 定义悬停检测回调
@app.callback(
    Output('hover-output', 'children'),
    Input('hover-image-graph', 'hoverData'),
    State('hover-image-graph', 'figure')
)
def detect_image_hover(hover_data, figure):
    if not hover_data:
        return "未悬停在任何元素上"
    
    # 获取鼠标悬停的坐标
    hover_x = hover_data['points'][0]['x']
    hover_y = hover_data['points'][0]['y']
    
    # 计算图片的边界范围(x从左到右,y从上到下)
    img_x_start = image_params['x']
    img_x_end = image_params['x'] + image_params['sizex']
    img_y_start = image_params['y'] - image_params['sizey']
    img_y_end = image_params['y']
    
    # 判断鼠标是否在图片范围内
    if (img_x_start <= hover_x <= img_x_end) and (img_y_start <= hover_y <= img_y_end):
        print("hello world")  # 执行自定义逻辑
        return "悬停在布局图片上啦!"
    else:
        return "悬停在图表数据点上"

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

代码说明

  1. 提前存储布局图片的坐标参数,方便后续对比鼠标位置;
  2. 通过Dash的dcc.Graph渲染图表,并监听其hoverData事件;
  3. 在回调函数中提取鼠标悬停的坐标,与图片的边界范围做对比;
  4. 若坐标落在图片范围内,执行预设逻辑并更新页面提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:51:18