nagix / chartjs-plugin-streaming

Chart.js plugin for live streaming data
MIT License
546 stars 132 forks source link

Insert old data as default before start streaming #115

Open leyendeckermarc opened 4 years ago

leyendeckermarc commented 4 years ago

I wonder how to get this working: When the chart is loaded it should draw a set of old/past data as a default and then start streaming new values, adding them to the old data.

Help really appreciated!

spoon252 commented 4 years ago

I did that in following way:

  1. I pull the "old" data from database (last 1 hour of data) and push it to the chart using temporary object chartdata:

       var chartdata = [];
       variables.forEach(variable => {
            chartdata.push({
                x: variable.timeStamp,
                y: variable.value
            });

This is the way that you push data to regular charts (data config is just where i store colors etc):

    this.chart.data.datasets.push({
            measureId: dataConfig.measureId,
            originalUnit: dataConfig.originalMeasurementUnit,
            newUnit: dataConfig.measuringUnitId,
            data: chartdata, //the actual data to push to chart
            fill: false,
            borderColor: dataConfig.color,
            borderWidth: dataConfig.borderWidth,
            label: dataConfig.label,
            backgroundColor: dataConfig.backgroundColor
        });
  this.chart.update();

Now there is 1 hour of data in the chart. You can find it in "chart.data.datasets[0].data". You can append new data to this by just pushing new values. I get the values from SignalR service and push them to chart using something like following:

 chart.data.datasets[0].data.push({
       x: _timeStamp,
       y: _value
  });

Note that you have to specify options for realtime plugin. Option "ttl" is important so you can see past data. I set my ttl to 60minutes so I can always see t-1h of data. Also specify duration so you can decide how much of past's data you want to see. Hope it helps