Search code examples
pythonplotlyplotly-python

Convert plotly marker from continuous to discrete


Following is my input file i'm trying to display on a map using plotly.

data.csv
lat,long,type
-7.80715,110.371203,1
-7.791087,110.368346,3
-7.778744,110.365107,7
-7.77877,110.365379,4

The script works but the scale is displayed in a continuous format. I tried to convert the column type to text as mentioned here but I couldn't get it to work. Is there a easier way to fix this problem?

df = pd.read_csv("data.csv").dropna()
fig = go.Figure(go.Scattermapbox(
        lat=df["lat"].tolist(),
        lon=df["long"].tolist(),
        mode='markers',
        text=df['type'].tolist(),
        marker=go.scattermapbox.Marker(
            size=10,
            color=df['type'],
            showscale=True
        ),
    ))

fig.show()

Solution

  • If you want to specify a discrete color, you can either deal with it directly as a list of color specifications, or you can specify the default color name in plotly_express.

    import plotly.graph_objects as go
    import plotly.express as px
    
    mapbox_access_token = open("mapbox_api_key.txt").read()
    colors = px.colors.qualitative.D3
    
    fig = go.Figure(go.Scattermapbox(
            lat=df["lat"].tolist(),
            lon=df["long"].tolist(),
            mode='markers',
            text=df['type'].tolist(),
            marker=go.scattermapbox.Marker(
                size=10,
                color=colors, 
                showscale=False
            ),
        ))
    
    fig.update_layout(
        autosize=False,
        height=450,
        width=1000,
        mapbox=dict(
            accesstoken=mapbox_access_token,
            style="outdoors",
            center=dict(
                lat=-7.78,
                lon=110.365
            ),
            zoom=10),
        showlegend = False
    )
    
    fig.show()
    

    enter image description here