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

How to overlay, or plot moving dot on top of a current plot using Javascript?

I just started learning plotly. I am using Javascript.

After a plot is made, using the command Plotly.newPlot('graph',data,layout); which is a static plot, I’d like to add a point on top of it. This point will be changing position with time. This is done by clicking on a button which causes requestAnimationFrame(update); to run all the time.

The problem is that, I do not know how to add the moving plot, on top of the current plot. I tried using Plotly.restyle('graph',data,layout) and tried Plotly.redraw('graph',data,layout).

I can create a newPlot for the moving dot OK, and I see it working OK. But then I would lose the original plot.

I am trying to create something like the following

The following is what I have. This is complete HTML page which contains everything.

<html>
<head>
               <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="graph" style="width:600px;height:500px;"></div>
<button onclick="javascript:update()">Run</button>
<script>

g_n = 2000;
g_i = 1;
g_x=[]; g_y=[]; g_z=[];
g_x[0]=1; g_y[0]=1; g_z[0]=1;

function make_initial_plot() 
{
  var a = 10, b = 8/3, r = 28;
  var x = [], y = [], z = [];
  var data = [{ x: x,   y: z, mode: 'markers', marker: {size: 2}}];  
  var layout = {xaxis: {range: [-40, 40]},yaxis: {range: [0, 60]}};
  
  x[0]=1; y[0]=1; z[0]=1;  
  
  for (var i = 1; i < g_n; i++) 
  {
    x[i] = x[i-1]+(a*y[i-1]-a*x[i-1])/100;
    y[i] = y[i-1]+(-x[i-1]*z[i-1]+r*x[i-1]-y[i-1])/100;
    z[i] = z[i-1]+(x[i-1]*y[i-1]-b*z[i-1])/100;
  };
  
  Plotly.newPlot('graph',data,layout);  
};

function update () 
{
  //THis is supposed to plot ONE point on top of current lorenz system plot.
  //But do not know how to make it plot on top of current plot
  var a = 10, b = 8/3, r = 28;
  var i;
  var data;
  var layout = {xaxis: {range: [-40, 40]},yaxis: {range: [0, 60]}};
  
  if (g_i==g_n) //reset if reached end
  {
      g_i = 1;
  };
    
  i = g_i;
  g_x[i] = g_x[i-1]+(a*g_y[i-1]-a*g_x[i-1])/100;
  g_y[i] = g_y[i-1]+(-g_x[i-1]*g_z[i-1]+r*g_x[i-1]-g_y[i-1])/100;
  g_z[i] = g_z[i-1]+(g_x[i-1]*g_y[i-1]-b*g_z[i-1])/100;
    
  g_i = g_i+1;    
  data = [
    {
      x: [g_x[i-1]],
      y: [g_z[i-1]],
      //type: 'scatter',
      mode: 'markers',
      marker: {size: 5, color: 'red'}
    }
  ];
    
  console.log(g_i,g_x[i],g_y[i]);
  //Plotly.restyle('graph',data,layout);  
  Plotly.newPlot('graph',data,layout);  // THis works, but deletes last plot
  requestAnimationFrame(update);
};


make_initial_plot();

</script>

</body>
</html>

Which clicking the run button, I wanted to have the point move without losing the original plot. I.e. either superimpose or overlay the point on top. Each time instance, only one single point is plotted.

How to do this in plotly?

Thanks
–Nasser