Search code examples
python-3.xplotlylegend

Plotly - clicking on legend items - how to make an initial setting?


When someone clicks on a legend item, it becomes grey, and the data disappears, for instance, here. It is possible to set that an item from a legend will be grey after opening the .HTML output and will appear after clicking of that? Thank you


Solution

  • You can do that using the visible property on the trace, just set visible='legendonly'.

    visible

    Type: enumerated , one of ( True | False | "legendonly" )
    Default: True
    Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible).

    A common use case is when one has a lot of traces and wants to show only a few of them initially, eg. with plotly.express :

    import plotly.express as px
    
    df = px.data.gapminder().query("continent == 'Europe'")
    
    # Nb. This creates one trace per country (color='country'), with each trace `name` 
    # inheriting the value of its respective country.
    fig = px.line(df, x='year', y='gdpPercap', color='country', symbol="country")
    
    # Arbitrary selection
    sel = ['Norway', 'Ireland', 'France', 'Switzerland']
    
    # Disable the traces that are not in the selection
    fig.update_traces(selector=lambda t: t.name not in sel, visible='legendonly')
    
    fig.show()