'Javascript real time chart with timeseries with random data problem

I try to figure how to randomize and tick the timeseries with setInterval function but i get only errors. And if the timeseries x axis is inserted manually and not random then the y random data doesn't looks right. Also what alternative i can use.

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<style>
#chart {
        }
</style>
</head>
<body>
<div class="wrapper">

    <div id="chart">
    <script>
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));

}
var datax = randomDate(new Date(1990, 0, 1), new Date());
          function getData() {
            return Math.random();
            
        }  
        Plotly.plot('chart',[{
            y:[getData()],
            x:[datax],
            type:'scatter'
            
            
        }]);


        var cnt = 0;
         
        setInterval(function(){
        
            Plotly.extendTraces('chart',{ y:[[getData()]]},  [0]);
            cnt++;
            
            if(cnt > 5) { //start interval
                Plotly.relayout('chart',{
                    xaxis: {
                        range: [cnt-10000,cnt] //range interval
                    }
                });
            }
            
        },1); //flow interval 1000 = 1sec
    </script>
</div>
</body>
</html>

https://jsfiddle.net/hyletyles/ynu4q2pL/6/



Solution 1:[1]

The following code adds a new data point every 100ms and starts shifting the plot using relayout after the first 100 points where added.

function rand() {
  return Math.random();
}

var time = new Date();

var data = [{
  x: [time], 
  y: [rand()],
  mode: 'line',
  line: {color: '#80CAF6'}
}]

Plotly.plot('chart', data);  

var cnt = 0;

var interval = setInterval(function() {
  
  var time = new Date();
  
  var update = {
  x:  [[time]],
  y: [[rand()]]
  }
  
  Plotly.extendTraces('chart', update, [0])
  
  if(cnt > 100) {
    Plotly.relayout('chart',{
        xaxis: {
        range: [cnt-100,cnt]
      }
    });
  }
}, 1000);

The above code is based on the "Streaming with Timestamp" example from the official Plotly.js docs.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gilbert Tanner