我想将新数据添加到现有图表中。这意味着我想将现有渲染的数据点与新数据点合并,以将旧数据点和新数据点渲染在一起。我正在尝试使用 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.x
、y
和text
之前的方括号
现在让我们开始享受添加数据的乐趣。我们首先从 const dataPoints 中创建一个变量来存储初始数据集(我稍微修改了大小)。在函数 tester(
) 中,我们随机添加一个点并更新/重绘图形。
<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
关于node.js - 如何使用plot.ly向现有图表添加新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38642237/