如何在绘图/破折号中默认选择图例中的一项?

oTo*_*TiX 1 python plotly plotly-dash

如何默认选择图例中的一项,而取消选择其他项目?

我希望最初的情节看起来像这样:

在此输入图像描述

#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)
Run Code Online (Sandbox Code Playgroud)

Ham*_*zah 5

您可以通过visible属性来实现这一点,如下所示:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述