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

Python中如何在地图上绘制代表城市出行路径的LineString线串

你之前代码的核心问题

  1. 调用px.line_mapbox时仅传入了起点经纬度,没有传入终点坐标,无法生成两点之间的连线
  2. 代码混用了erg2和gdf两个不同的数据集变量,运行时会直接报错
  3. 构造LineString时经纬度顺序写反,shapely要求坐标格式为(经度, 纬度),你写的是(纬度, 经度),会导致坐标完全错位
  4. 没有提前过滤move=0的无效记录,会绘制无意义的路径

适配你数据集的可运行代码

直接替换你本地的erg2数据集即可运行,完全匹配你提到的三个需求:

import geopandas as gpd
import shapely.geometry
import numpy as np
import plotly.express as px

# 1. 过滤move>0的有效记录,跳过无出行的路径
erg2_valid = erg2[erg2['move'] > 0].reset_index(drop=True)

# 2. 构造标准GeoDataFrame,纠正经纬度顺序
gdf = gpd.GeoDataFrame(
    data=erg2_valid,
    geometry=erg2_valid.apply(
        lambda r: shapely.geometry.LineString(
            [(r["longitude_origin"], r["latitude_origin"]),
             (r["longitude_destination"], r["latitude_destination"]) ]), axis=1)
)

# 3. 提取绘图所需的坐标、hover信息、出行人次值
lats = []
lons = []
hover_names = []
move_values = []

for feature, od_name, move_cnt in zip(gdf.geometry, 
                                      gdf["origin"].astype(str) + " - " + gdf["destination"].astype(str),
                                      gdf["move"]):
    if isinstance(feature, shapely.geometry.linestring.LineString):
        linestrings = [feature]
    elif isinstance(feature, shapely.geometry.multilinestring.MultiLineString):
        linestrings = feature.geoms
    else:
        continue
    for linestring in linestrings:
        x, y = linestring.xy
        lats = np.append(lats, y)
        lons = np.append(lons, x)
        hover_names = np.append(hover_names, [od_name]*len(y))
        move_values = np.append(move_values, [move_cnt]*len(y))
        # 插入None分隔不同线路,避免无关路径连在一起
        lats = np.append(lats, None)
        lons = np.append(lons, None)
        hover_names = np.append(hover_names, None)
        move_values = np.append(move_values, None)

# 4. 绘图:按出行人次区分颜色和线宽,hover显示起点终点信息
fig = px.line_mapbox(
    lat=lats, 
    lon=lons, 
    hover_name=hover_names,
    color=move_values,
    color_continuous_scale="RdYlBu_r", # 可自行调整配色方案
    line_width=2 + move_values/erg2_valid['move'].max()*5, # 人次越高线路越粗,可调整比例
    center =dict(lon=13.41053,lat=52.52437), 
    zoom=3, 
    height=600
)

fig.update_layout(
    mapbox_style="stamen-terrain", 
    mapbox_zoom=4, 
    mapbox_center_lat = 52.52437,
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig.show()

如果需要调整线路的显示效果,修改color_continuous_scale和line_width的参数即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:39:03