dc.js:具有多个CSV的ReduceSum

时间:2015-06-19 22:09:58

标签: javascript d3.js dc.js crossfilter

这是另一个StackOverflow problem的后续工作,可以将包含多个CSV的图表创建到单个dc.js仪表板中。

我按照说明操作,我的图表正在运行。但是,不起作用的是numberDisplay元素。我怀疑的是,由于我将两个CSV的总计制表,我必须调整groupAll.reduceSum()函数,但我不确定如何。我的代码示例如下

//using queue.js to load data
var q = queue()
  .defer(d3.csv, "data1.csv")
  .defer(d3.csv, "data2.csv");

  q.await(function(error, data1, data2){

  //initiatizing crossfilter and ingesting data
  var ndx = crossfilter();
  ndx.add(data1.map(function(d){
    return { age: d.age,
             gender: d.gender,
             scores: +d.scores,
             total: +d.total,
             type: 'data1'};
    }));

  ndx.add(data2.map(function(d){
    return { age: d.age,
             gender: d.gender,
             scores: +d.scores,
             total: +d.total,
             type: 'data2'};
    }));

//initializing charts
totalDisplay = dc.numberDisplay("#total-display");
totalScores = dc.numberDisplay("#total-scores");

//groupAll function to sum up the values
var scoresGroup = ndx.groupAll().reduceSum(function(d) {
          d.scores;
        });
        var totalGroup = ndx.groupAll().reduceSum(function(d) { 
          d.total;
        });

//parameters for the number display. Currently it is returning NaN
totalDisplay
        .formatNumber(d3.format(","))
        .valueAccessor(function(d) {
            return d;
        })
        .group(totalGroup);

totalScores
        .formatNumber(d3.format(",f"))
        .valueAccessor(function(d) {
            return d;
        })
        .group(scoresGroup);

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您需要使用return才能从函数中返回值!

var scoresGroup = ndx.groupAll().reduceSum(function(d) {
      d.scores;
});
var totalGroup = ndx.groupAll().reduceSum(function(d) { 
      d.total;
});

应该是

var scoresGroup = ndx.groupAll().reduceSum(function(d) {
      return d.scores;
});
var totalGroup = ndx.groupAll().reduceSum(function(d) { 
      return d.total;
});

否则,您将最终汇总undefined并且undefined不是数字。 : - )