✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐇 Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

Plotly express how to separate symbol and color in legend

I’m using python and plotly.express, I use categorical variables for both symbol and color, but the legend doesn’t separate symbol and color, they are grouped together. Is there way to show a legend for symbol and color separately, similar to this question: https://stackoverflow.com/questions/47539539/separate-symbol-and-color-in-plotly-legend

The code there is in R, but I’m using python and plotly.express. I tried to use similar method listed in the stackoverflow and use go.scatter, and first draw the lines, then draw points, however, I don’t know how to make go.scatter take a color that’s a column with categorical values in my dataframe, or take a marker shape that’s a column with categorical values in my dataframe. Please advise. Thank you

Hi @songsy welcome to the forum! This is not possible at the moment because one legend item corresponds to one trace. If you want to emulate this behaviour, you’ll have to modify the name of traces and to add dummy traces so that the symbol appears in the legend, as in the example below

import plotly.express as px
df = px.data.tips()
fig = px.scatter(df, x='total_bill', y='tip', color='day', symbol='sex')
for i, trace in enumerate(fig.data):
    name = trace.name.split(',')
    if name[1] == ' Male':
        trace['name'] = ''
        trace['showlegend']=False
    else:
        trace['name'] = name[0]
fig.add_trace(go.Scatter(y=[None], mode='markers',
                         marker=dict(symbol='circle', color='black'),
                         name='Female',
                         ))
fig.add_trace(go.Scatter(y=[None], mode='markers',
                         marker=dict(symbol='diamond', color='black'),
                         name='Male',
                         ))
fig.update_layout(legend_title_text='')
fig.show()

2 Likes

Thank you so much! Really appreciate it!

1 Like