如何用Plotly scatter_mapbox仅将目的地坐标与原点坐标连线
解决Mapbox地图中仅连接起点与所有终点的问题
我正在使用scatter_mapbox创建带连线的地图,目前已实现所有坐标间相互连线,但需求是仅将数据集中key列为Destination的坐标与key列为Origin的唯一坐标相连。
测试数据
import pandas as pd lat_dest = [21.028321, 10.426675, 10.776390,-35.297591,21.028321] lon_dest = [105.854022,-75.544342,106.701139,149.101268,105.854022] locations = ['Hanoi, Vietnam','Cartagena, Colombia','Ho Chi Minh City, Vietnam','Canberra, Australia','Hanoi, Vietnam'] dest_key = ['Destination','Destination','Destination','Destination','Origin'] test_df = pd.DataFrame({ 'lat': lat_dest, 'lon': lon_dest, 'name': locations, 'key':dest_key })
现有地图代码
import plotly.express as px import plotly.graph_objects as go fig = px.scatter_mapbox( test_df, lat="lat", lon="lon", color="key", zoom=2, center = {"lat": orig_lat, "lon": orig_lon} ) fig.update_layout( mapbox_style="carto-positron", margin={"r":0,"t":0,"l":0,"b":0}, showlegend=False ) fig.add_trace(go.Scattermapbox( mode = "lines", lon = new_df['lon_dest'], lat = new_df['lat_dest'] ))
解决方案
要实现仅连接起点与所有终点,需先提取唯一的起点坐标,再为每个终点生成「起点-终点」的坐标对序列来绘制连线,具体实现代码如下:
import pandas as pd import plotly.express as px import plotly.graph_objects as go # 测试数据 lat_dest = [21.028321, 10.426675, 10.776390,-35.297591,21.028321] lon_dest = [105.854022,-75.544342,106.701139,149.101268,105.854022] locations = ['Hanoi, Vietnam','Cartagena, Colombia','Ho Chi Minh City, Vietnam','Canberra, Australia','Hanoi, Vietnam'] dest_key = ['Destination','Destination','Destination','Destination','Origin'] test_df = pd.DataFrame({ 'lat': lat_dest, 'lon': lon_dest, 'name': locations, 'key':dest_key }) # 提取唯一的起点坐标 origin_row = test_df[test_df['key'] == 'Origin'].iloc[0] orig_lat, orig_lon = origin_row['lat'], origin_row['lon'] # 创建基础散点地图 fig = px.scatter_mapbox( test_df, lat="lat", lon="lon", color="key", zoom=2, center = {"lat": orig_lat, "lon": orig_lon} ) fig.update_layout( mapbox_style="carto-positron", margin={"r":0,"t":0,"l":0,"b":0}, showlegend=False ) # 为每个终点添加到起点的连线 destinations = test_df[test_df['key'] == 'Destination'] for _, row in destinations.iterrows(): fig.add_trace(go.Scattermapbox( mode = "lines", lon = [orig_lon, row['lon']], lat = [orig_lat, row['lat']], line = dict(width=2, color='blue') )) fig.show()
代码说明
- 通过
test_df[test_df['key'] == 'Origin'].iloc[0]精准获取唯一的起点经纬度 - 筛选所有
Destination行,循环生成每条从起点到终点的连线轨迹 - 可通过
line参数自定义连线的宽度、颜色等样式,适配不同可视化需求
内容的提问来源于stack exchange,提问作者user2813606
相关产品推荐
相关产品推荐

