转储chartjs数据中缺少的日期

dump missing date in data for chartjs

本文关键字:日期 chartjs 数据 转储      更新时间:2023-09-26

假设我将使用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点。

我只需要一些逻辑来处理这类问题,例如,在全年处理几点时。

这可以在实际图形之外完成,方法是预先解析标签以检查它们的日期是否连续。在下面的例子中,我使用了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>