Control legend for particular range of x axis for different traces using plotly javascript library

Viewed 199

I want to control the legends of different traces all at once for particular range lets say x=0 to x=5. How can we do it?

var trace1 = {
  x: [0, 1, 2, 3, 4, 5, 6, 7, 8],
  y: [0, 3, 6, 4, 5, 2, 3, 5, 4],
  type: 'scatter'
};
var trace2 = {
  x: [0, 1, 2, 3, 4, 5, 6, 7, 8],
  y: [0, 4, 7, 8, 3, 6, 3, 3, 4],
  type: 'scatter'
};
var trace3 = {
  x: [0, 1, 2, 3, 4, 5, 6, 7, 8],
  y: [5, 7, 3, 2, 8, 6, 1, 9, 3],
  type: 'scatter'
};

var data = [trace1, trace2, trace3];
var layout = {showlegend: true,
    legend: {"orientation": "h"}};
 
Plotly.newPlot('myDiv', data, layout);

For example, when we click a legend, the encircled portion should get hid. Image

Sample code: Codepen_Sample

Update 2: what if trace(curve) is defined by set of different sub-traces whose ranges of the legends to be controlled are different but trace[name] are same for all the curves. For e.g this is the pseudo code:

for(let i=0; i<5; i++){
    initialise trace1;
    trace2;
    trace3;
}
1 Answers

You can break up each of your three traces into starting and ending segments, then assign the starting segments the same name, same legendgroup, and only display one of these in the legend using the showlegend attribute.

Since plotly.js will make each trace a new color by default, you probably want to make the starting and ending segments of each trace to be the same color. Fixing the xaxis range will avoid having the entire plot resize when you toggle the legend entry.

Here is the javascript and codepen sample:

var trace1_start = {
  x: [0, 1, 2, 3, 4, 5],
  y: [0, 3, 6, 4, 5, 2],
  type: 'scatter',
  marker: {color: 'orange'},
  name: 'start',
  showlegend: true,
  legendgroup: 'start'
};
var trace1_end = {
  x: [5, 6, 7, 8],
  y: [2, 3, 5, 4],
  type: 'scatter',
  marker: {color: 'orange'},
  name: 'trace1',
};
var trace2_start = {
  x: [0, 1, 2, 3, 4, 5],
  y: [0, 4, 7, 8, 3, 6],
  marker: {color: 'steelblue'},
  type: 'scatter',
  name: 'start',
  showlegend: false,
  legendgroup: 'start'
};
var trace2_end = {
  x: [5, 6, 7, 8],
  y: [6, 3, 3, 4],
  type: 'scatter',
  marker: {color: 'steelblue'}
};
var trace3_start = {
  x: [0, 1, 2, 3, 4, 5],
  y: [5, 7, 3, 2, 8, 6],
  type: 'scatter',
  marker: {color: 'forestgreen'},
  name: 'start',
  showlegend: false,
  legendgroup: 'start'
};
var trace3_end = {
  x: [5, 6, 7, 8],
  y: [6, 1, 9, 3],
  type: 'scatter',
  marker: {color: 'forestgreen'}
};

var data = [trace1_start, trace1_end, trace2_start, trace2_end, trace3_start, trace3_end];
var layout = {showlegend: true,
    legend: {"orientation": "h"}, xaxis: {"range": [0,8]}};
 
Plotly.newPlot('myDiv', data, layout);

enter image description here

Related