|
| 1 | +--- |
| 2 | +name: Legend Click Events |
| 3 | +plot_url: https://codepen.io/plotly/embed/vazxKv/?height=500&theme-id=15263&default-tab=result |
| 4 | +language: plotly_js |
| 5 | +suite: events |
| 6 | +order: 4.1 |
| 7 | +sitemap: false |
| 8 | +arrangement: horizontal |
| 9 | +markdown_content: | |
| 10 | + `plotly_legendclick` and `plotly_legenddoubleclick` allow customization of the plotly legend. The default behaviour of `plotly_legendclick` is to hide a trace and the default behavior of `plotly_legenddoubleclick` is to select one trace and hide all the others. |
| 11 | + We can add to the default behaviour by creating a new `plotly_legendclick` event with a function of our choice. We can also disable the default behaviour by creating a function that returns `false`. In the example below, we do both in order to create a `plotly_legendclick` event which changes the marker color back to black instead of erasing the trace. |
| 12 | +--- |
| 13 | +var myPlot = document.getElementById('myDiv'), |
| 14 | + x = [1, 2, 3, 4, 5, 6], |
| 15 | + y = [1, 2, 3, 2, 3, 4], |
| 16 | + y2 = [1, 4, 7, 6, 1, 5], |
| 17 | + colors = [['#5C636E','#5C636E','#5C636E','#5C636E','#5C636E','#5C636E'], |
| 18 | + ['#393e46','#393e46','#393e46','#393e46','#393e46','#393e46']], |
| 19 | + data = [{x:x, y:y, type:'scatter', |
| 20 | + mode:'line', line:{ color:'#5C636E'},marker:{size:16, color:colors[0]}}, |
| 21 | + {x:x, y:y2, type:'scatter', |
| 22 | + mode:'line',line:{ color:'#393e46'}, marker:{size:16, color:colors[1]}}], |
| 23 | + layout = { |
| 24 | + showlegend: true, |
| 25 | + hovermode:'closest', |
| 26 | + title:'Click on a Point to Change Color<br>Click on a Trace in the Legend to Change Back One Trace Only' |
| 27 | + }; |
| 28 | + |
| 29 | +Plotly.newPlot('myDiv', data, layout); |
| 30 | + |
| 31 | +myPlot.on('plotly_click', function(data){ |
| 32 | + var pn='', |
| 33 | + tn='', |
| 34 | + colors=[]; |
| 35 | + for(var i=0; i < data.points.length; i++){ |
| 36 | + pn = data.points[i].pointNumber; |
| 37 | + tn = data.points[i].curveNumber; |
| 38 | + colors = data.points[i].data.marker.color; |
| 39 | + }; |
| 40 | + colors[pn] = '#C54C82'; |
| 41 | + var update = {'marker':{color: colors, size:16}}; |
| 42 | + Plotly.restyle('myDiv', update,[tn]); |
| 43 | +}); |
| 44 | + |
| 45 | +myPlot.on('plotly_legendclick', function(data){ |
| 46 | + var trColors = [['#5C636E','#5C636E','#5C636E','#5C636E','#5C636E','#5C636E'], |
| 47 | + ['#393e46','#393e46','#393e46','#393e46','#393e46','#393e46']]; |
| 48 | + var update = {'marker':{color: trColors[data.curveNumber], size:16}}; |
| 49 | + Plotly.restyle('myDiv', update,[data.curveNumber]); |
| 50 | + return false; |
| 51 | +}); |
0 commit comments