Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dump missing date in data for chartjs

Supposing that I will use line chart from ChartJS, and I have 'value by date' data. example:

5   : 05-11-2014
10  : 04-11-2014
55  : 01-11-2014

the chart will be contain 3 points.

is there any solution, configuration that let me add automatically add (dump) missing date with value = 0, so the data for the example will be :

5   : 05-11-2014 
10  : 04-11-2014 
0   : 03-11-2014 
0   : 02-11-2014
55  : 01-11-2014

and of course the chart will contain 5 points.

I just need some logic to handle this kind of problem exactly when dealing with few points by whole year for example.

like image 633
NITS Avatar asked Nov 05 '14 12:11

NITS


People also ask

What is utils in ChartJS?

The Utils file contains multiple helper functions that the chart. js sample pages use to generate charts. These functions are subject to change, including but not limited to breaking changes without prior notice.


1 Answers

This can be done outside of the actual graph by pre-parsing you labels to check that they are sequential in date. In the example below i have made use of momentjs as it just makes date manipulation, formatting and parsing so much easier.

then it is just a case of when finding a date that is not followed by a squential date to add it in to the labels and also the graph data.

var graphData = [55, 10, 5],
  labels = ["01-11-2014", "04-11-2014", "05-11-2014"];


for (var i = 0; i < labels.length; i++) {
  //make sure we are not checking the last date in the labels array
  if (i + 1 < labels.length) {
    var date1 = moment(labels[i], "DD-MM-YYYY");
    var date2 = moment(labels[i + 1], "DD-MM-YYYY");

    
    //if the current date +1 is not the same as it's next neighbor we have to add in a new one
    if (!date1.add(1, "days").isSame(date2)) {
      
      //add the label
      labels.splice(i + 1, 0, date1.format("DD-MM-YYYY"));
      //add the data
      graphData.splice(i + 1, 0, 0);
    }
  }


}


var ctx = document.getElementById("chart").getContext("2d");
var data = {
    labels:labels,
    datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,0.8)",
        highlightFill: "rgba(220,220,220,0.75)",
        highlightStroke: "rgba(220,220,220,1)",

        data: graphData
    }]
};


var myLineChart = new Chart(ctx).Line(data);

console.log(labels);
console.log(graphData);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js"></script>
<script src="https://raw.githack.com/leighquince/Chart.js/master/Chart.min.js"></script>
<canvas id="chart" width="500px"></canvas>
like image 149
Quince Avatar answered Oct 21 '22 03:10

Quince