如何使用plot.ly将新数据添加到现有graphics

我想添加新的数据到现有的graphics。 这意味着我想将现有的渲染数据点与新的数据点合并,以将旧的和新的数据点渲染在一起。 我正在尝试使用Plotly.newPlot来渲染这样的新数据:

 const TESTER = document.getDocumentById('tester'); const dataPoints = { x: [1, 2, 3], y: [1, 2, 3], text: ['1 text', '2 text', '3 text '], size: [1, 2, 3], color: [1, 2, 3] }; const layout = { margin: { t: 0 }, hovermode: 'closest' }; const dataToRender = { x: [dataPoints.x], y: [dataPoints.y], text: [dataPoints.text], mode: 'markers', marker: { size: dataPoints.size, color: dataPoints.color, sizemode: 'area', showscale: true, colorscale: 'Portland', colorbar: { xanchor: 'right', len: 0.5, title: 'km' } } }; Plotly.newPlot(TESTER, dataToRender, layout); 

但我总是收到一个plotly-latest.min.js:32 Uncaught TypeError: Cannot read property 'style' of undefined 。 我究竟做错了什么?

提前致谢

情节的格式有时有点棘手。 您需要更改数据结构,如下所示:

 const dataToRender = [{ x: dataPoints.x, y: dataPoints.y, text: dataPoints.text, mode: 'markers', marker: { size: dataPoints.size, color: dataPoints.color, sizemode: 'area', showscale: true, colorscale: 'Portland', colorbar: { xanchor: 'right', len: 0.5, title: 'km' } } }]; 

即所有的数据都进入一个包含数据本身和元信息,布局等的数组。

  • 在你的dataToRender添加方括号
  • {x ...marker}周围添加大括号
  • 删除dataPoints.xytext之前的方括号

现在让我们开始添加数据的乐趣。 我们首先从const dataPoints数据点中创build一个variables来存储初始数据集(我稍微修改了这个大小)。 在函数tester( )中,我们随机添加一个点并更新/重绘graphics。

 <script> var dataPoints = { x: [1, 2, 3], y: [1, 2, 3], text: ['1 text', '2 text', '3 text '], size: [50, 250, 500], color: [1, 2, 3] } var t = setInterval(tester, 1000); function tester() { const TESTER = document.getElementById('tester'); dataPoints.x.push(Math.random() * 3); dataPoints.y.push(Math.random() * 3); dataPoints.size.push(Math.random() * 500); dataPoints.color.push(1 + Math.random() * 2); const layout = { margin: { t: 0 }, hovermode: 'closest' }; const dataToRender = [{ x: dataPoints.x, y: dataPoints.y, text: dataPoints.text, mode: 'markers', marker: { color: dataPoints.color, size: dataPoints.size, sizemode: 'area', showscale: true, colorscale: 'Portland', colorbar: { xanchor: 'right', len: 0.5, title: 'km' } } }]; Plotly.newPlot(TESTER, dataToRender, layout); } </script> 


这是JSfiddle的工作

Interesting Posts