Responsive Time Series with JavaScript and Plotly

by Génesis García Morilla

HTML

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="chart"></div>

CSS

body {
  margin: 0;
  padding: 0;
}

#chart {
  width: 100vw;
  height: 100vh;
}

JavaScript

// New line plot with random data between 0 and 1
Plotly.newPlot('chart', [{
  x: [new Date()],
  y: [Math.random()],
  mode: 'lines',
  line: { color: 'grey' }
}], { 
  title: 'Streaming simulation with random data',
  font: { size: 16, color: 'grey' }
}, { 
  responsive: true 
})

// Streaming simulation with setInterval
setInterval(() => {
  Plotly.extendTraces('chart', {
    x: [[new Date()]],
    y: [[Math.random()]]
  }, [0])
}, 1e3)