是否可以在D3.js中将日期范围用作时间刻度上的单个日期项目?

时间:2017-01-03 17:01:01

标签: javascript d3.js

我有一张如下图所示的图表,但我遗漏了一个关键因素。我当前的时间刻度是标准的(第1张图片),但我需要将其转换为第2张图片中可见的时间刻度。这在D3中甚至可能吗?我正在使用D3.js V3。

enter image description here

multi line chart

1 个答案:

答案 0 :(得分:1)

据我所知,D3不包含动态自动汇总自定义时间间隔的任何功能,但似乎你可以通过一些基本的javascript简单地完成这个...

    var data = [
            {date: new Date(2016, 11, 10), value: 1},
            {date: new Date(2016, 11, 11), value: 2},
            {date: new Date(2016, 11, 12), value: 3},
            {date: new Date(2016, 11, 13), value: 3},
            {date: new Date(2016, 11, 14), value: 2},
            {date: new Date(2016, 11, 15), value: 3},
            {date: new Date(2016, 11, 16), value: 5},
            {date: new Date(2016, 11, 16), value: 4},
            {date: new Date(2016, 11, 17), value: 2},
            {date: new Date(2016, 11, 19), value: 3},
            {date: new Date(2016, 11, 20), value: 1},
            {date: new Date(2016, 11, 21), value: 3}
        ];

    rollup(data, 3);

    function rollup(data, days) {
        var min = data.reduce(function(a, b) {if (b.date < a) return b.date; return a;}, new Date(3000, 1, 1)),
            max = data.reduce(function(a, b) {if (b.date > a) return b.date; return a;}, new Date(1000, 1, 1)),
            output = [];
        for (var day = min; day < max; day.setDate(day.getDate() + days)) {
            var end = new Date(day);
            end.setDate(end.getDate() + days);
            var working = data.filter(function(a) {return (a.date >= day && a.date < end);}),
                value = working.reduce(function(a, b) {return a + b.value;}, 0);
            output.push({date: day.toString() + ' - ' + end.toString(), value: value});
        }
        console.log(output);
        return output;
    }