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

如何在Plotly line_mapbox中为德国铁路路线添加平均延误指标?

Plotly line_mapbox实现铁路路线延误标注与配色区分

这两个需求在Plotly的line_mapbox中完全可行,以下是具体实现方案:

一、基于延误范围的热力图配色区分路线

通过绑定延误数据到线条颜色参数,可实现不同延误程度的路线自动匹配配色,直观区分差异:

  • 使用color参数绑定每条路线的平均延误数值
  • 通过color_scale指定热力配色方案(可选用Plotly内置配色如RdYlGn_r,红-黄-绿反向,延误越高颜色越红)
  • 添加colorbar标注配色对应的延误范围,提升可读性

示例代码片段:

import plotly.graph_objects as go

# 假设你的路线数据存储在列表中,每条路线包含坐标与平均延误
routes = [
    {"coords": [[lon1, lat1], [lon2, lat2], ...], "delay": 5},
    {"coords": [[lon3, lat3], [lon4, lat4], ...], "delay": 12},
    # 其他3条路线数据
]

fig = go.Figure()

for route in routes:
    lons, lats = zip(*route["coords"])
    fig.add_trace(go.Scattermapbox(
        lon=lons,
        lat=lats,
        mode="lines",
        line=dict(width=4),
        color=[route["delay"]],  # 绑定延误数值
        color_scale="RdYlGn_r",
        name=f"延误{route['delay']}分钟"
    ))

fig.update_layout(
    mapbox_style="carto-positron",
    mapbox_center={"lat": 51.1657, "lon": 10.4515},  # 德国中心坐标
    mapbox_zoom=5,
    coloraxis_colorbar=dict(title="平均延误时长(分钟)")
)

fig.show()

二、文本形式标注平均延误时长

有两种常用实现方式:

1. 鼠标悬停显示(推荐)

将延误信息添加到hover tooltip中,鼠标划过路线时自动显示:
在Scattermapbox中添加text参数,指定显示内容:

fig.add_trace(go.Scattermapbox(
    # 其他参数不变
    text=f"平均延误: {route['delay']}分钟",
    hoverinfo="text+name"  # 同时显示名称与延误信息
))

2. 固定文本标注

在路线的中心位置添加静态文本标注,需先计算每条路线的中心点坐标:

# 计算路线中心点
def get_center(coords):
    lons = [p[0] for p in coords]
    lats = [p[1] for p in coords]
    return sum(lons)/len(lons), sum(lats)/len(lats)

annotations = []
for route in routes:
    center_lon, center_lat = get_center(route["coords"])
    annotations.append(dict(
        x=center_lon,
        y=center_lat,
        text=f"{route['delay']}min",
        showarrow=False,
        font=dict(size=12, color="black")
    ))

fig.update_layout(annotations=annotations)

你可以根据需求选择单独使用配色区分,或结合文本标注,让地图信息更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 06:53:23