Vega-Lite Stream Data

Replace Previous Set with new Set

by NesterOne

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vega/3.0.1/vega.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vega-lite/2.0.0-beta.15/vega-lite.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vega-embed/3.0.0-beta.20/vega-embed.js"></script>
  
<div id="viz"></div>

JavaScript

var vlSpec = {
   '$schema': 'https://vega.github.io/schema/vega-lite/v2.json',
    data :{
         values: [
          {val: 1}, {val: 5}, {val: 3},
          {val: 4}, {val: 5}, {val: 6},
          {val: 7}, {val: 8}, {val: 9}
        ]
    },
    mark: 'bar',
    encoding: {
      x: {bin: true, field: 'val', type: 'quantitative'},
      y: {aggregate: 'count', type: 'quantitative'}
    }
};
vega.embed('#viz', vlSpec).then(function(res) {
    function randomGenerator() {
       var result = [];
       var i = 0;
       while(i < 100){
       	result.push({val: Math.random() * 10});
        i++;
       }
       return result;
    }
 
    window.setInterval(function () {
        var view = res.view;
        var prevData = view.data('source_0');
        var newData = randomGenerator();
        var changeSet = vega.changeset();
        changeSet.remove(prevData)
        changeSet.insert(newData);
        view.change('source_0', changeSet).run();
    }, 1000);
});