angulartypescriptcanvasjs

How to add zero-values when there is no data available? (Canvas.js)


I have a Canvas.js Stock Chart(line-chart) in which I display interactions(y-axis) per time(x-axis).

I get an Array<Date>and group the dates per hour. Depending on how many dates in the array have the same hour, I can say how many interactions there were, which I show with a dot in the chart.

If in one particular hour there were no Interactions at all it doesn't set a dot at zero. It connects the line directly to the next value and of course this displays the data incorrectly.

So my question is if there is a native way to set the hours - which don't have any interactions - to zero. If not, how do I fill the gaps manually with zeros?

Here is how my Chart looks like right now: Stock Chart

Here is the fiddle: https://jsfiddle.net/gx9hqs6o/39/


Solution

  • So my question is if there is a native way to set the hours - which don't have any interactions - to zero.

    In CanvasJS, the dataPoints passed are rendered as such without any manipulation done to the dataPoints.

    If not, how do I fill the gaps manually with zeros?

    You will have to loop through the dataPoints array and for all the missing data (gaps) you can add the missing dataPoint with the y-value as 0.

    Below is a code-snippet,

    function addMissingDps(stockChart) {    
          for(var i = 0; i <stockChart.options.charts[0].data.length; i++) {
            var newDps = [];    
            var dps = stockChart.options.charts[0].data[i].dataPoints;
    
            /* Find Missing hours in a the dps array */
            var missingDates = dps.sort(function(a,b){
              return Date.parse(a.x) - Date.parse(b.x);
            }).reduce(function(hash){
              return function(p,c){
                var missingHoursNo = (Date.parse(c.x) - hash.prev) / (1000 * 60 * 60);
                if(hash.prev && missingHoursNo > 1) {
                  for(var i = 1; i < missingHoursNo; i++)
                    p.push(new Date(hash.prev + i * (1000 * 60 * 60)));
                }
                hash.prev = Date.parse(c.x);
                return p;
              };
            }(Object.create(null)),[]);
    
            /* Add missing dataPoints to the dataPoints array */    
            for(var j = 0; j < missingDates.length; j++) {
              dps.push({x: missingDates[j], y: 0})      
            }    
    
            /* Sort newly added dates */
            dps.sort(function(a,b){      
              return Date.parse(a.x) - Date.parse(b.x);
            });
          }  
        }
    

    You can take a look at this JSFiddle for a working example.