Add_trace for multiple px.line_mapbox figures with geographic lines

I am trying to highlight particular lines in a px.line_mapbox, I tried using color discrete but couldn’t figure that out using a geodataframe. So I thought to merge two line graphs into one of different colors, but this doesn’t seem to work either. What is the best way to color a few lines in a px.line_mapbox based on a particular attribute from a callback?

def getLines(gdf):
    lats = []
    lons = []
    names = []

    for feature, name in zip(gdf.geometry, gdf.Name):
        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)
            names = np.append(names, [name]*len(y))
            lats = np.append(lats, None)
            lons = np.append(lons, None)
            names = np.append(names, None)
    return lats, lons, names


gdf = src_gdf.query('names != "Line 1"')

lats, lons, names = getLines(gdf)


boxfig = px.line_mapbox(lat=lats, lon=lons, hover_name=names, 
                        mapbox_style="stamen-terrain", zoom=5)
boxfig.update_traces(line_color='#0000ff', line_width=2)


getdf = geo_df2.query('names == "Line 1"')
lat, lon, _ = getLines(getdf)
boxfig2 = px.line_mapbox(lat=lat, lon=lon,)
boxfig2.update_traces(line_color='#FF5733', line_width=2)
boxfig.add_trace(boxfig2)

What i am trying to do is load the start and end points for geographic locations, then highlight certain routes based on my callbacks.

Would anyone know the best way to do this?

Hello @wongkong ,

I am not entirely sure if I understood you correctly. But based on this

I understand that you would like to define the color of a specific trace (line) in your plot. With the selector parameter you can do so.

import plotly.express as px
import pandas as pd

# data source
us_cities = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")

# two states for different traces
ny = us_cities.query("State in ['New York']")
oh = us_cities.query("State in ['Ohio']")


# create figure
fig = px.line_mapbox(ny, lat="lat", lon="lon", zoom=3, height=300)

# add trace
fig.add_trace(px.line_mapbox(oh,lat='lat', lon='lon').data[0])

# define color of each trace
fig.update_traces(line=dict(color='purple'), selector=0)
fig.update_traces(line=dict(color='red'), selector=1)

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

fig.show()

Which creates

Yeah, it was user error

1 Like