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

Plotly混合Scattermapbox与Scatter子图时悬停提示失效问题求助

问题原因与修复方法

当子图中包含Scattermapbox组件时,Plotly的全局悬停逻辑会被默认调整,导致笛卡尔坐标系的线图无法触发悬停提示。以下是两种可行的修复方案:

方案一:为线图显式指定悬停信息类型

给每个Scatter trace添加hoverinfo='x+y'属性,强制渲染悬停提示:

import numpy as np
from plotly.subplots import make_subplots
import plotly.graph_objects as go


fig = make_subplots(
    rows=2, cols=2,
    specs=[
        [{'rowspan':2, 'type' :'mapbox'},{'type' : 'scatter'}],
        [None,{'type' : 'scatter'}],
    ],
    print_grid=True,
)

x = np.linspace(0,2*np.pi,100)
y1 = np.sin(x)
y2 = np.cos(x)

fig.add_trace(
    go.Scatter(
        x=x,
        y=y1,
        hoverinfo='x+y'  # 新增:指定悬停显示x和y值
    ),
    row=1, col=2,
)


fig.add_trace(
    go.Scatter(
        x=x,
        y=y2,
        hoverinfo='x+y'  # 新增:指定悬停显示x和y值
    ),
    row=2, col=2,
)

coordinates = {
    'Berlin' : (52.5200, 13.4050),
    'Munich' : (48.1351, 11.5820),
    'Hamburg' : (53.5488, 9.9872),
    'Frankfurt' : (50.1109, 8.6821),
    'Dresden' : (51.0504, 13.7373),
}

z, lat, lon, names = zip(*[
    (i,v[0],v[1],k) for i,(k,v) in enumerate(coordinates.items())])
    
fig.add_trace(
    go.Scattermapbox(
        lat = lat,
        lon = lon,
        mode = 'markers+text',
        text = names,
        below = '',
        marker_size=12,
        marker_color=z,
        name = 'town',
    ),
    col=1, row=1,
)

fig.update_layout(margin=dict(l=20, r=0, t=40, b=40))
    
fig.update_layout(
    mapbox1=dict(
        zoom=4, style='carto-positron',
        center={k:v for k,v in zip(['lat','lon'],coordinates['Frankfurt'])}, 
    ),
)

fig.show()

方案二:全局设置悬停模式

在布局中添加hovermode参数,统一配置所有子图的悬停行为:

# ... 其余代码与原示例一致 ...

fig.update_layout(
    margin=dict(l=20, r=0, t=40, b=40),
    hovermode='x unified'  # 新增:全局设置悬停模式为x轴统一触发
)
    
fig.update_layout(
    mapbox1=dict(
        zoom=4, style='carto-positron',
        center={k:v for k,v in zip(['lat','lon'],coordinates['Frankfurt'])}, 
    ),
)

fig.show()

两种方案都能让线图恢复正常的悬停提示,同时不影响Scattermapbox的交互功能。

内容的提问来源于stack exchange,提问作者Thomas Kühn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 22:24:59