【发布时间】:2015-02-14 21:09:31
【问题描述】:
附上示例数据
var data = [
{Name: 'Mr A', Spent: 40, Year: 2011, tags: ['a', 'b', 'c']},
{Name: 'Mr B', Spent: 10, Year: 2011, tags: ['c']},
{Name: 'Mr C', Spent: 40, Year: 2011, tags: ['a']},
{Name: 'Mr A', Spent: 70, Year: 2012, tags: ['c', 'b']},
{Name: 'Mr B', Spent: 20, Year: 2012, tags: ['b']},
{Name: 'Mr B', Spent: 50, Year: 2013, tags: ['a', 'b', 'c']},
{Name: 'Mr C', Spent: 30, Year: 2013, tags: ['a', 'b']}
];
我正在尝试创建一个 dc.js 行图,该图表将显示每个唯一标签并允许我减少每个标签绘制的值。到目前为止,我有这段代码可以让我将标签减少到他们花费的总和:
function reduceAdd(p, v) {
v.tags.forEach (function(val, idx) {
p[val] = (p[val] || 0) + v.Spent;
});
return p;
}
function reduceRemove(p, v) {
v.tags.forEach (function(val, idx) {
p[val] -= v.Spent;
});
return p;
}
function reduceInitial() {
return {};
}
var tagsDim = ndx.dimension(function(d) {return d.tags; } );
tagsGroup = tagsDim.groupAll().reduce(reduceAdd, reduceRemove, reduceInitial);
console.log(tagsGroup.value())
'{ a: 160, b: 210, c: 170 }'
这正确地给出了减少的总和。但是,因为这是一个 groupAll 对象 dc.js 无法绘制它,所以我不太确定从这里去哪里。 dc.js 甚至可以访问数组中的标签吗?以不同的方式计算总和会更好吗?
【问题讨论】:
-
这样你会得到不相交的组——因为一行可以属于与标签一样多的组,所以行将被计算多次。此外,任何其他跨行进行普通总和的图表都会得到不同的总数。这是你想要的吗?
-
很确定 crossfilter 不支持这个,所以你必须自己实现它。很容易适应您作为fake group 获得的组;棘手的部分是写filter function。
-
谢谢@Gordon,我会试试的。
标签: javascript dc.js crossfilter