在dc.js中,为什么elasticX对时间序列图表不能正常工作

时间:2015-05-29 01:05:45

标签: dc.js

这是jfiddle - http://jsfiddle.net/inasisi/6v639g9g/1/

如您所见,X轴未正确缩放。我可以计算最小和最大日期并正确设置比例但不想在每个过滤器后执行此操作。如果elasticX正常工作,则更喜欢。

有什么想法吗?

var chartGroup = "chartGroup";

data = [{
    "run_date": "2013-01-20",
    "current_grade": "Kindergarten",
    "students": 1
}, {
    "run_date": "2013-01-20",
    "current_grade": "First",
    "students": 2
}, {
    "run_date": "2014-03-22",
    "current_grade": "Kindergarten",
    "students": 3
}, {
    "run_date": "2014-03-22",
    "current_grade": "First",
    "students": 4
}, {
    "run_date": "2015-10-06",
    "current_grade": "Kindergarten",
    "students": 5
}, {
    "run_date": "2015-10-06",
    "current_grade": "First",
    "students": 21
}, {
    "run_date": "2015-02-13",
    "current_grade": "Kindergarten",
    "students": 31
}, {
    "run_date": "2015-02-13",
    "current_grade": "First",
    "students": 26
}, ];

var ndx = crossfilter(data);
var dateFormat = d3.time.format("%Y-%m-%d");
data.forEach(function (d) {
    d.run_date = Date.parse(d.run_date);
});

var ndx = crossfilter(data);

filterDateDimension = ndx.dimension(function (d) {
    return [d.run_date];
});

dateDimension = ndx.dimension(function (d) {
    return [d.run_date];
});

var minDate = dateDimension.bottom(1)[0].run_date;
var maxDate = dateDimension.top(1)[0].run_date;

var runsStudentsGroup = dateDimension.group().reduceSum(function (fact) {
    return fact.students;
});

var totalStudentsChart = dc.lineChart("#students_chart", chartGroup);

totalStudentsChart.renderArea(true)
    .width(300)
    .height(300)
    .x(d3.time.scale())
    .elasticY(true)
    .elasticX(true)
    .renderHorizontalGridLines(true)
    .renderVerticalGridLines(true)
    .dimension(dateDimension)
//.colors('red')
.group(runsStudentsGroup);

dc.renderAll(chartGroup);

$('.day_filter').on('click', function () {
    console.log(dateDimension.top(Infinity));
    console.log($(this).val());

    dateDimension.filter(function (d) {
        console.log(d > new Date(2015, 0, 1));
        return d > new Date(2015, 0, 1);
    });

    console.log(dateDimension.top(Infinity));
    dc.redrawAll();
});

1 个答案:

答案 0 :(得分:1)

我必须修改一些东西才能显示图表并让过滤器完全正常工作。我只是引用那些没有解释的,因为那些不是问题所在:

d.run_date = new Date(d.run_date);
//...
return d.run_date; // twice
//...
filterDateDimension.filter(function (d) {
//...
dc.redrawAll(chartGroup);

要回答经常被问到的主要问题,crossfilter不会自动删除空箱。您可以使用"fake group"过滤掉它们。

添加:

function remove_empty_bins(source_group) {
    return {
        all:function () {
            return source_group.all().filter(function(d) {
                return d.value != 0;
            });
        }
    };
}
//...
.group(remove_empty_bins(runsStudentsGroup));

你小提琴的工作叉:http://jsfiddle.net/gordonwoodhull/8an2n1eL/5/

(此示例中的转换特别棘手,will be fixed in 2.1。)