Search code examples
pythonpandasplotlymapboxline

Connect coordinates on scatter_mapbox using lines but only connecting from origin


I am working on creating a map that connects coordinates using a line with scattermapbox. Using the example here, I have been able to connect each coordinate to one another.

However, I just want to connect coordinates that have the value of "Destination" under the column "Key" to the one coordinate in my dataset that has the value of "Origin" for that same column.

Here is my data:

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
})
 

Here is the map:

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']
))

Solution

  • To draw a line from one point to another, you must specify the latitude and longitude of the origin and the latitude and longitude of each end point. So, if the data is in your list format, it can be simplified by a loop process. Finally, thank you for the opportunity to respond.

    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": test_df['lat'].mean(), "lon": test_df['lon'].mean()}
    )
    
    fig.update_layout(
        mapbox_style="carto-positron",
        margin={"r":0,"t":0,"l":0,"b":0},
        showlegend=False
    )
    
    for lon,lat in zip(lon_dest[1:-1],lat_dest[1:-1]):
        fig.add_trace(go.Scattermapbox(mode="lines",
                                       lon=[lon_dest[-1],lon],
                                       lat=[lat_dest[-1],lat],
                                       line_color='blue')) 
    
    fig.show()
    

    enter image description here