我想将新数据添加到现有图表中。这意味着我想将现有的渲染数据点与新的数据点合并,以将旧数据点和新数据点一起渲染。我尝试使用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
。我做错了什么?
提前致谢
答案 0 :(得分:2)
情节格式有时有点棘手。您需要更改数据结构,如下所示:
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