Reputation: 153
I want to add new data to an existing graph. Meaning that I want to merge the existing rendered data points with new ones to render the old and the new data points together. I'm trying to use Plotly.newPlot
to render new data like this:
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);
But I always end up receiving a plotly-latest.min.js:32 Uncaught TypeError: Cannot read property 'style' of undefined
. What am I doing wrong?
Thanks in advance
Upvotes: 3
Views: 4053
Reputation: 31659
The plotly format is sometimes a bit tricky. You need to change the data structure as follows:
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'
}
}
}];
i.e. all data goes in an array which contains the data itself and the metainformation, layout, etc.
dataToRender
{x ...marker}
dataPoints.x
, y
and text
Now let's get to the fun of adding data. We first make a variable out of your const dataPoints
to store the initial data set (I modified the size a little bit). In the function tester(
) we randomly add one point and update/redraw the graph.
<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>
Here is the working JSfiddle
Upvotes: 3