如何更新第二个坐标轴的数据javascript?

How to update the data of the second axes plotly javascript?

代码如下:

var trace1 = {
  x: [1, 2, 3],
  y: [40, 50, 60],
  name: 'yaxis data',
  type: 'scatter'
};

var trace2 = {
  x: [2, 3, 4],
  y: [4, 5, 6],
  name: 'yaxis2 data',
  yaxis: 'y2',
  type: 'scatter'
};

var data = [trace1, trace2];

var layout = {
  title: 'Double Y Axis Example',
  yaxis: {title: 'yaxis title'},
  yaxis2: {
    title: 'yaxis2 title',
    titlefont: {color: 'rgb(148, 103, 189)'},
    tickfont: {color: 'rgb(148, 103, 189)'},
    overlaying: 'y',
    side: 'right'
  }
};

Plotly.newPlot('myDiv', data, layout);
<head><script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head>
<div id="myDiv"></div>

我只想更新第二个轴上的数据yaxis2。我想避免数据冗余,因此我不想转发其他数据。

请让我知道我能做什么。

您要查找的是Plotly.react,或Plotly.addTraces/Plotly.deleteTraces。这是 docs.

为了更新数据,你不能改变数据。您需要创建一个新的不可变数据实例 (reference)。

因此您可以制作数据副本并通过:

Plotly.react('myDiv', data.map((trace, i) => {
  if (i != 1) return trace;
  return <new trace>
})

或者,您可以删除跟踪并重新添加它:

const newTrace = {...} // some trace object
Plotly.deleteTraces('myDiv', 1); // remove at index 1
Plotly.addTraces('myDiv', newTrace);

下面是在 1 秒超时后更新绘图的示例:

var trace1 = {
  x: [1, 2, 3],
  y: [40, 50, 60],
  name: 'yaxis data',
  type: 'scatter'
};

var trace2 = {
  x: [2, 3, 4],
  y: [4, 5, 6],
  name: 'yaxis2 data',
  yaxis: 'y2',
  type: 'scatter'
};

var data = [trace1, trace2];

var layout = {
  title: 'Double Y Axis Example',
  yaxis: {title: 'yaxis title'},
  yaxis2: {
    title: 'yaxis2 title',
    titlefont: {color: 'rgb(148, 103, 189)'},
    tickfont: {color: 'rgb(148, 103, 189)'},
    overlaying: 'y',
    side: 'right'
  }
};

Plotly.newPlot('myDiv', data, layout);

setTimeout(() => {
  const newTrace = {
    x: [2, 3, 4],
    y: [4, 10, 20],
    name: 'yaxis2 data',
    yaxis: 'y2',
    type: 'scatter'
  }
  // delete the second trace (index 1) or delete multiple traces with Plotly.deleteTraces('myDiv', [0,1])
  Plotly.deleteTraces('myDiv', 1); 
  // add a new trace
  Plotly.addTraces('myDiv', newTrace);
}, 1000)
<head><script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head>
<div id="myDiv"></div>