如何在dc.js中决定维度和分组?

How to decide dimensions and groups in dc.js?

我是 dc.js 的新手,在决定维度和组方面遇到了问题。我有这样的数据

this.data = [
    {Type:'Type1', Day:1, Count: 20},
    {Type:'Type2', Day:1, Count: 10},
    {Type:'Type1', Day:2, Count: 30},
    {Type:'Type2', Day:2, Count: 10}
]

我必须显示两个折线图的组合图表,一个用于类型 1,另一个用于类型 2。我的 x 轴将是日。所以我的维度之一是 Day

var ndx = crossfilter(this.data);
var dayDim = ndx.dimension(function(d) { return d.Day; }) 

如何分组?如果我在 Count 上执行此操作,则会显示我不想要的特定日期的总计数。

您的问题不完全清楚,但听起来您想同时按 TypeDay

分组

一种方法是使用复合键:

var typeDayDimension = ndx.dimension(function(d) {return [d.Type, d.Day]; }),
    typeDayGroup = typeDayDimension.group().reduceSum(function(d) { return d.Count; });

然后你可以使用系列图表在一个复合图表中生成两个折线图。

var chart = dc.seriesChart("#test");
chart
    .width(768)
    .height(480)
    .chart(function(c) { return dc.lineChart(c); })
    // ...
    .dimension(typeDayDimension)
    .group(typeDayGroup)
    .seriesAccessor(function(d) {return d.key[0];})
    .keyAccessor(function(d) {return +d.key[1];}) // convert to number
    // ...

有关详细信息,请参阅 the series chart example

尽管 Gordon 的建议非常有效,但如果您想使用复合图表获得相同的结果,那么您可以使用 group.reduce(add, remove, initial) 方法。

function reduceAdd(p, v) {
  if (v.Type === "Type1") {
    p.docCount += v.Count;
  } 
  return p;
}

function reduceRemove(p, v) {
  if (v.Type === "Type1") {
    p.docCount -= v.Count;
  } 
  return p;
}

function reduceInitial() {
  return { docCount: 0 };
}

举个例子:http://jsfiddle.net/curtisp/7frw79q6

引用 :

Series chart is just a composite chart with the automatic splitting of the data and generation of the child charts.