javascriptplotlyonclicklistener

How to get which trace is clicked in legend in plot.ly JS


In plot.ly, you are able to add a listener for legend click events. How can I find out which trace in the legend I clicked? For a more concrete example, suppose I have two traces (trace0, trace1) in a line graph. When the user clicks trace0 in the legend, I want to display an alert saying "trace0". Similarly, when the user clicks trace1 in the legend, I want an alert saying something different. I can make alerts just fine but I can't find any documentation on how plot.ly identifies which trace is clicked in the legend. Any help?


Solution

  • According to the documentation about Event Handlers you can use data, which contains information about the event.

    var trace1 = {
      x: [1, 2, 3, 4],
      y: [10, 15, 13, 17],
      type: 'scatter'
    };
    
    var trace2 = {
      x: [1, 2, 3, 4],
      y: [16, 5, 11, 9],
      type: 'scatter'
    };
    
    var data = [trace1, trace2];
    
    Plotly.newPlot('myDiv', data);
    
    var myPlot = document.getElementById('myDiv');
    
    myPlot.on('plotly_click', function(data) {
        // get event information from data
        console.log(data);
    });
    

    CodePen