在chartjs的数据中转储缺失日期 [英] dump missing date in data for chartjs

查看:59
本文介绍了在chartjs的数据中转储缺失日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

是否有任何解决方案,配置允许我添加自动添加(转储)缺少日期与
值= 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>

这篇关于在chartjs的数据中转储缺失日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆