2014-11-05 60 views
4

假設我將使用ChartJS的折線圖,並且我有'按日期值'數據。 示例:轉儲chartjs的數據丟失日期

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

圖表將包含3點。

是否有任何溶液,配置,讓我自動添加添加(轉儲)失蹤日期 值= 0,因此對於示例中的數據將是:

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

和當然的圖表將包含5分。

我只是需要一些邏輯來處理這種問題,正確地處理全年的幾個點時,例如。

回答

3

這可以通過預先解析標籤來檢查它們在日期中是連續的,從而在實際圖形之外完成。在下面的例子中,我使用了momentjs,因爲它只是對日期進行操作,所以格式化和解析更容易。

那麼它只是一個當找到一個日期時沒有按順序日期將其添加到標籤和圖形數據的情況。

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>