🏥 🏭 Working on the COVID-19 response in Canada? Plotly & the Canadian government can help you and your organization. Learn more and get in touch.

Dash - callback on legend item clicked

I have a graph with a few traces plotted on it.
Im trying to setup a callback function which will be triggered every time a legend item is clicked on, and will print the names of traces which are currently visible.

digging in the documentation, i haven’t succeded achieving it (not enough javascript knowledge apparently)

can someone please provide a code\source\idea for how to accomplish it?

Hi @avivazran welcome to the forum! Changing the visibility of a trace in the legend triggers a restyleData event as in the minimal app below. You can listen to this event in your callback.

import json
from textwrap import dedent as d

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

styles = {
    'pre': {
        'border': 'thin lightgrey solid',
        'overflowX': 'scroll'

app.layout = html.Div([
            'data': [
                    'x': [1, 2, 3, 4],
                    'y': [4, 1, 3, 5],
                    'text': ['a', 'b', 'c', 'd'],
                    'customdata': ['c.a', 'c.b', 'c.c', 'c.d'],
                    'name': 'Trace 1',
                    'mode': 'markers',
                    'marker': {'size': 12}
                    'x': [1, 2, 3, 4],
                    'y': [9, 4, 1, 4],
                    'text': ['w', 'x', 'y', 'z'],
                    'customdata': ['c.w', 'c.x', 'c.y', 'c.z'],
                    'name': 'Trace 2',
                    'mode': 'markers',
                    'marker': {'size': 12}
            'layout': {
                'clickmode': 'event+select'

    html.Div(className='row', children=[
                **Click Data**

                Click on points in the graph.
            html.Pre(id='click-data', style=styles['pre']),
        ], className='three columns'),

    Output('click-data', 'children'),
    [Input('basic-interactions', 'restyleData')])
def display_restyle_data(restyleData):
    return json.dumps(restyleData, indent=2)

if __name__ == '__main__':

1 Like