Hide legend trace in plot with multiple types

Hi,
This is the code to recreate my example

import pandas as pd
import plotly.express as px

def shorten(string):
    short = string.split()[0]
    return short

df = pd.read_csv('https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/penguins_raw.csv', )
df['Species'] = df['Species'].apply(shorten)

trait1 = 'Culmen Length (mm)'
trait2 = 'Flipper Length (mm)'

fig = px.scatter(df, x=trait1, y=trait2, color='Species')

trace_contour = px.density_contour(df, x=trait1, y=trait2, color='Species').update_layout(showlegend=False).select_traces()

fig.add_traces(list(trace_contour))

I created a figure using px.scatter() and then I wanted to add some contour traces in my figure.
To do this I selected the traces of a px.density_contour() plot and I added them to my figure, that now looks like this.

Iā€™d like to only show the legend of the scatter plot and not the legend of the density_contour plot.
I tried adding .update_layout(showlegend=False) to the px.density_contour() function before selecting the trace but nothing happened.
Do you know how to hide the legend items of the traces added to the original figure?

Hi @Mirk0_98 ,

changing from

trace_contour = px.density_contour(df, x=trait1, y=trait2, color='Species').update_layout(showlegend=False).select_traces()

to

trace_contour = px.density_contour(df, x=trait1, y=trait2, color='Species').update_traces(showlegend=False).select_traces()

Produces the desired output.

That is, because the information of showlegend is stored in the trace. Here you can see this exemplary for the first trace:

traces = px.density_contour(df, x=trait1, y=trait2, color='Species').select_traces()
print(next(traces))

Histogram2dContour({
    'contours': {'coloring': 'none'},
    'hovertemplate': ('Species=Adelie<br>Culmen Lengt' ... '}<br>count=%{z}<extra></extra>'),
    'legendgroup': 'Adelie',
    'line': {'color': '#636efa'},
    'name': 'Adelie',
    'showlegend': True,
    ...
    ...
1 Like