Search code examples
pythonobjectplotlylegendtrace

Python Plotly object with legend for different marker_color


I want to add a legend for each marker_color on my second trace below but I can't figure out how to make it happen through the graph objects. Any idea?

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(
    go.Scattergeo(
        lat = df_outliers['Lat'], 
        lon = df_outliers['Long'], 
        marker = {'color' : 'grey',
                   'size': 5, 
                  'symbol': 'diamond'},
        name = "Stations outside clusters"
                )
            )

fig.add_trace(
    go.Scattergeo(
        lat = df_clusters['Lat'], 
        lon = df_clusters['Long'],
        mode = 'markers',
        marker_color = df_clusters['Clus_Db']
                )
            )

fig.update_layout(width=800, height=500,
                  margin=dict(r=0, b=20, l=0, t=50),
                  title = {
                     'text': "Weather Station in Canada",
                     'y':0.95,
                     'x':0.5,
                     'xanchor': 'center',
                     'yanchor': 'top' },
                 geo_scope='north america'
                 )
fig.show()

enter image description here


Solution

  • Moved around by using a for loop and specifying the type of marker when we are on the outliers value:

    import plotly.graph_objects as go
    import pandas as pd
    
    fig = go.Figure()
    
    for C in list(df.Clus_Db.unique()):
        # Adding trace for outlier
        if C==-1:
            fig.add_trace(go.Scattergeo(
                            lat = df[df.Clus_Db == C]['Lat'],
                            lon = df[df.Clus_Db == C]['Long'],
                            name = 'Stations outside clusters',
                            marker = {'color' : 'grey','size': 5,'symbol': 'diamond'}
                                        )
                            )
            
        # Adding trace for clusters
        else:
            fig.add_trace(go.Scattergeo(
                            lat = df[df.Clus_Db == C]['Lat'],
                            lon = df[df.Clus_Db == C]['Long'],
                            name = 'Cluster ' + str(C))
                         )
        
    fig.update_layout(width=800, height=500,
                      margin=dict(r=0, b=20, l=0, t=50),
                      title = {
                         'text': "Weather Station in Canada",
                         'y':0.95,
                         'x':0.5,
                         'xanchor': 'center',
                         'yanchor': 'top' },
                     geo_scope='north america'
                     )
    
    fig.show() 
    

    enter image description here