Black Lives Matter. Please consider donating to Black Girls Code today.

How to exchange the data dynamically, keeping the same trace number?


I’m trying to solve the following problem for a long time, trying out different approaches. However, none of them led me to a proper solution.
My goal is to visualize the periodically (e.g. every 1 ms) changing data on the same layout. This means I have 2 traces and the new updated data must not be added to the old one, but should exchange the old data points. I tried out Plotly,restyle(), Plotly.deleteTraces() Plotly.redraw() and even Plotly.newPlot(), but the data of the second trace is still appended to the old data. The data of the first trace is correct.
Please give me a hint, how to solve it. Thanks.

Here is my example code:

// Setup top plot
var TopPlotLayout = {
title: ‘Top View’,
showlegend: false,
xaxis: {
title: ‘Lateral distance[m]’,
range: [-30, 30],
dtick: 5,
gridcolor: ‘#bdbdbd’},
yaxis: {
title: ‘Longitudinal distance [m]’,
range: [-100, 100],
dtick: 10,
gridcolor: ‘#bdbdbd’}
Plotly.newPlot(‘TopPlot’, [ { x:[10000, 10000],y:[10000, 10000], mode: ‘markers’} ], TopPlotLayout);

function valueChanged(json_string)
           // here extracting the data from JSON String etc....

             var TopPlotData = {
	  x: AngleArray,
	  y: DistanceArray,
	  mode: 'markers',
	  marker: {size: 10, symbol: 'square-cross'}
	var TopPlotRawData = {
	  x: AngleArrayRaw,
	  y: DistanceArrayRaw,
	  mode: 'markers',
	  marker: {size: 5, color: 'rgb(211, 104, 204)'}

         var TopPlot = document.getElementById('TopPlot');

   [0] = TopPlotData; // replace by new data[1] = TopPlotRawData; // replace by new data



restyle should do what you describe.

Here’s an example:

Hello Etienne,

thank you very much for your fast reply and help.

In your code example, there is a delay of 1 sec for plotting. In my application the data arrives with a data rate of about 50 ms. Anyway, faster than 1 sec. Might it be the problem?

With best regards,


I’m sorry for havin bothered you. It was my fault, my wrong implementation, which led to such an undesired behaviour.
I was pushing the new data into the global declared array. Therefore, the amount of data was growing continously.
I had to clear the array in each function call, of course! :smiley:

Best regards,