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

Time:11-05

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)

CodePudding user response:

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

  • Related