javascript - 使用plotly javascript库控制不同轨迹的x轴特定范围的图例

标签 javascript plotly plotly.js

我想同时控制特定范围内不同迹线的图例,比如 x=0 到 x=5。我们怎样才能做到呢?

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);

例如,当我们单击图例时,圈出的部分应该隐藏。 Image

示例代码:Codepen_Sample

更新 2:如果迹线(曲线)是由一组不同的子迹线定义的,这些子迹线要控制的图例范围不同,但所有曲线的迹线[名称]相同,会怎么样。例如,这是伪代码:

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

最佳答案

您可以将三个轨迹中的每一个分解为起始段和结束段,然后为起始段分配相同的名称、相同的图例组,并且仅显示其中之一在图例中使用 showlegend 属性。

由于默认情况下,plotly.js 会将每条迹线设置为新颜色,因此您可能希望将每条迹线的起始段和结束段设置为相同的颜色。修复 x 轴范围将避免在切换图例条目时调整整个绘图的大小。

这是 javascript 和 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

关于javascript - 使用plotly javascript库控制不同轨迹的x轴特定范围的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68283659/

相关文章:

php - 如何获取带有在选择框中选择的值的文本框

python - 如何将数学风格(如 Latex)的单位添加到 Plotly 图表中而不侵 eclipse 标签的其余部分?

python - 属性错误: module 'pandas' has no attribute 'np' - Cufflinks spread graph

python - Jupyter Lab 中未显示 Plotly 图表

python - 在折线/面积图的左右两侧添加填充

javascript - Plotly.js 时间序列图表上的渐变颜色

javascript - 使用{{render}}时如何访问非单例的父 Controller ?

javascript - 我不明白这个 javascript 函数是如何执行的

javascript - 使用 document.links 将当前页面的 URL 保存在 addon sdk 中