How to have one item in the legend selected by default in plotly/dash?

Question:

How to have one item in the legend selected by default and the others should be deselected?

I want the initial plot looking like this:

enter image description here

#prepare thr chart
fig = px.line(df, x='date', y='diesel_price', color='region', 
                title='Diesel price in the US', 
                labels={'date':'Date', 
                'diesel_price':'Price ($)', 'region':'Region'})

app.layout = html.Div([
    html.H4('Metrics for trucking companies'),
    dcc.Graph(figure=fig),
])

if __name__ == '__main__':
    app.run_server(debug=True, host='0.0.0.0', port=8050)
Asked By: oToMaTiX

||

Answers:

You can achive that through visible attribute as follows:

import plotly.express as px

df = px.data.gapminder().query("continent=='Oceania'")

fig = px.line(df, x="year", y="lifeExp", color='country')

fig.update_traces(visible="legendonly") #<----- deselect all lines 

fig.data[0].visible=True   #<------ display the first line
                   
fig.show()

enter image description here

Answered By: Hamzah
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.