Add trace(s) name in legend with plotly express when "color" is not specified

Hi guys,

exploring plotly.express…

I’m stuck with a very simple task. Can I add the trace name (with the name attribute) in the legend if I don’t specify the color paramter?:

tips = px.data.tips()
fig = px.bar(tips, "sex", "tip")
fig.update_layout(showlegend=True)
fig.show()

the legend is not visible. Am I missing something?

Thanks

Matteo

The Legend text for a trace comes from the name attribute so you will need to update that to whatever you want to set the legend to. You will also need to make sure the showlegend attribute within the trace (Not just in the layout. That one is for if you want the entire legend to be visible or not and it defaults to True in px.) is also set to True. You can do this like below:

import plotly.express as px
tips = px.data.tips()
fig = px.bar(tips, "sex", "tip")
fig.data[-1].name = 'Diner'
fig.data[-1].showlegend = True
fig.show()

Or, you can use update_traces. This updates all the traces in your plot to have the name=“Diner” but it doesn’t matter because there is only one trace at the moment.

import plotly.express as px
tips = px.data.tips()
fig = px.bar(tips, "sex", "tip")
fig.update_traces(name='Diner', showlegend = True)
fig.show()
1 Like

Thanks, works perfectly!

Any suggestion how to do this in a grouped violin plot, like

fig.update_traces(box_visible=False, box_width=0.1, box_line_color='magenta', box_line_width=1, 
                  meanline_visible=True,
                  points='all',
                  pointpos=-0,
                  jitter=0.5,
                  marker=dict(size=7, line_width=0.5, opacity=1),
                  meanline=dict(color='rgba(0,0,0,1)', width=2),
                  line_width=0.5,
                  #line_color='rgba(0,0,0,1)',
                  opacity=0.8,
                  bandwidth=1.5,
                  hoveron='violins+points',
                  #fillcolor='magenta',
                  name='Border',
                  showlegend=True)

gives