javascript - 如何更新第二个轴的数据plotly javascript?

标签 javascript plotly plotly.js

这是代码:

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.reactPlotly.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>

关于javascript - 如何更新第二个轴的数据plotly javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60846773/

相关文章:

javascript - 无法从 URL 获取某些参数 - 返回 NaN/null

python - 如何使用python绘制彼此相邻的绘图仪表图?

python - 如何在同一个 pandas 数据框的同一列的一个绘图图表中绘制多条线?

javascript - 自定义 parcats plotly.js 图表的悬停

javascript - AngularJS:这段代码有什么问题吗?

javascript - javascript中的回溯,无法更新全局变量

javascript - scrollX 和 pageXOffset 有什么区别

python - 将 Dash 布局保存到 html

javascript - 如果列有 'NULL' 则选择该行数据