Create overlapping boundaries by group in Plotly Python

Viewed 186

I am creating a scattermapbox with points that are in several different categories. I would like to create boundary outlines for each group, where the boundary color corresponds to the group color. The points in different groups do overlap sometimes, so the boundaries should overlap as well so each boundary line contains all the points within the group. I prefer to have no fill in the boundaries so the points are more visible. Below is the code for the mcve:

import random
import pandas as pd
import plotly
import plotly.graph_objs as go

# Create data
random.seed(341)
n = 100
lat = [random.uniform(30, 50) for i in range(n)]
lon = [random.uniform(-130, -100) for i in range(n)]
n_groups = 10 # in reality the number of groups is much larger, so a continuous color scale is necessary
group = random.choices(range(n_groups), k=n)
for i in range(len(group)):
    if lat[i] > 38 and lat[i] < 40 and lon[i] < -118 and lon[i] > -122:
        group[i] = 6
    if lat[i] > 36 and  lat[i] < 38 and lon[i] < -118 and lon[i] > -122:
        group[i] = 7 

location_df = pd.DataFrame({'lat': lat, 'lon': lon, 'group': group})

# Public mapbox access token
mapbox_access_token = # add your own token
hover_text = 'custom hover text' 

# Create figure
fig = go.Figure()

## Add trace 

loc_colors = location_df['group']/max(location_df['group'])

fig.add_trace(
    go.Scattermapbox(
        lat=location_df['lat'],
        lon=location_df['lon'],
        mode='markers',
        
        marker=dict(
            colorscale="jet",
            size=12,
            color=loc_colors,
            #symbol='marker' # Does not seem compatible with color
        ),
        hovertext=location_df['group'],
        hoverinfo='text'
    )
)

## General layout

fig.update_layout(
    hovermode='closest',
    width=750, # Size of entire graph
    height=750,
    showlegend=False,
    mapbox=dict(
        accesstoken=mapbox_access_token,
        bearing=10,
        pitch=60,
        zoom=3,
        center=dict(
            lat=np.mean(lat),
            lon=np.mean(lon)
        )
    )
)

fig.show()


Here is a picture of what it looks like right now:

enter image description here

Here is what I want it to look like (or something similar): enter image description here

0 Answers
Related