转储chartjs的数据中缺少的日期日期、数据、转储、chartjs

2023-09-07 11:46:08 作者:快手四字干净 快手四个字最火

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

图表将包含 3 个点.

the chart will be contain 3 points.

是否有任何解决方案,配置可以让我自动添加添加(转储)缺少的日期value = 0,因此示例的数据将为:

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

当然,图表将包含 5 个点.

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.

推荐答案

这可以在实际图表之外完成,方法是预先解析标签以检查它们是否在日期上是连续的.在下面的示例中,我使用了 momentjs,因为它使日期操作、格式化和解析变得更加容易.

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>

 
精彩推荐
图片推荐