简体   繁体   中英

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/

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM