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

plotly scattermapbox如何添加固定位置的annotation/text标注?

Plotly Scattermapbox 固定标注实现方案

固定在屏幕位置(不随地图平移/缩放改变位置)

使用paper坐标的annotation完全可以实现该需求,你当前的代码仅存在两处可修正的问题:

  • annotations 属性要求传入列表格式,哪怕只有1个标注也需要将配置字典套入列表中
  • 补充 xanchor、yanchor 参数可避免标注内容超出画布被裁剪

修正后的配置示例:

layout = {
    "autosize": True,
    "hovermode": "closest",
    "mapbox": {
        "accesstoken": MAPBOX_KEY,
        "bearing": 0,
        "center": {
            "lat": layout_lat,
            "lon": layout_lon
        },
        "pitch": 0,
        "zoom": zoom,
        "style": "outdoors",
    },
    # 修正为列表格式
    "annotations": [
        {
            "x": 1,
            "y": 0,
            "showarrow": False,
            "text": "Custom annotation text",
            "xref": "paper",
            "yref": "paper",
            # 新增锚点配置,让标注右下角对齐(1,0)坐标
            "xanchor": "right",
            "yanchor": "bottom"
        }
    ],
    "margin": {
        "r": 0,
        "t": 0,
        "l": 0,
        "b": 0,
        "pad": 0
    }
}

固定在地理坐标位置(锚定指定经纬度,随地图操作同步移动)

如果需要标注钉在指定的地理点位上,paper坐标的annotation无法实现该需求,推荐新增独立的scattermapbox文本 trace实现,适配回调更新场景:

# 在figure的data数组中新增该trace即可
text_trace = go.Scattermapbox(
    lat=[target_lat], # 要锚定的点位纬度
    lon=[target_lon], # 要锚定的点位经度
    mode="text",
    text=["固定在地理点位的标注内容"],
    textposition="top right",
    showlegend=False
)

该trace的text内容也可以在回调中动态更新,和你的现有scattermapbox trace更新逻辑完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:18:03