我正在尝试删除空箱或者我应该在dc.js dataTable中说出0值的行。
我根据示例编写了我的代码&在dc.js文档的 remove empty bins常见问题解答中提供了一些片段,但我仍然无法获得所需的结果。
我正在尝试使用假组对数据进行分组,然后按总金额的降序对表进行排序。
var data = [{salesman: "AB",name: "John",total: 190.1,type: "Tab"},
{salesman: "CD",name: "David",total: 190,type: "Tab"},
{salesman: "EF",name: "Elton",total: 300.5,type: "Visa"},
{salesman: "AB",name: "John",total: 90.0,type: "Tab"},
{salesman: "EF",name: "Elton",total: 90,type: "Tab"},
{salesman: "CD",name: "David",total: 90,type: "Tab"}];
var ndx = crossfilter(data);
var salesManDim = ndx.dimension(function(d) {
return d.salesman;
});
var salesmanSumGroup = salesManDim.group().reduceSum(function(d) {
return (Math.round((d.total) * 100) / 100);
});
var salesmanChart = dc.pieChart("#chart");
salesmanChart
.width(200)
.height(150)
.slicesCap(10)
.innerRadius(30)
.dimension(salesManDim)
.group(salesmanSumGroup);
var salesMan_TypeDim = ndx.dimension(function(d) {
return d.salesman + "/" + d.type;
});
var groupedDimension = salesMan_TypeDim.group().reduce(
function(p, v) {
p.TOTAL += +(Math.round((v.total) * 100) / 100);
p.SALESMAN = v.salesman + " - " + v.name;
p.TYPE = v.type;
return p;
},
function(p, v) {
p.TOTAL -= +(Math.round((v.total) * 100) / 100);
p.SALESMAN = v.salesman + " - " + v.name;;
p.TYPE = v.type;
return p;
},
function() {return { TOTAL: 0, SALESMAN: "",TYPE: ""};});
var rank = function(p) {
return p.key.substr(p.key.lastIndexOf("/") + 1);
};
function remove_empty_bins(source_group) {
function non_zero_pred(d) {
return d.value.TOTAL !== 0;
}
return {
top: function(n) {
return source_group.top(Infinity).filter(non_zero_pred).slice(0, n);
}
};
}
dc.dataTable(".dc-data-table")
.dimension(remove_empty_bins(groupedDimension))
.group(rank)
.size(Infinity)
.columns([
function(d) {
return d.value.SALESMAN;
},
function(d) {
return (Math.round((d.value.TOTAL) * 100) / 100);
}
])
.sortBy(function(d) {
return d.value.TOTAL;
})
.order(d3.descending);
dc.renderAll();
dc.redrawAll();
当我检入调试器但是仍然以某种方式不过滤0值时,删除空箱功能正常工作。是因为我的键被定义的方式? To best explain my scenario here is a jsFiddle for the above example
答案 0 :(得分:1)
令人惊讶的是,它出现在这样一个简单的例子中,但浮点加法和减法通常会导致值在你期望它们时不为零。
特别经常发生十进制数字。 0.1 is unrepresentable in binary floating point numbers, and they are not necessarily associative or distributive.
我们可以添加以下行来诊断问题:
.on('preRedraw', function(chart) {
console.log(chart.dimension().top(Infinity).map(x=>x.value.TOTAL));
})
事实上,当我们点击CD时,我们会看到:
[200, 370.3, 2.842170943040401e-14]
所以这样写non_zero_pred
:
function non_zero_pred(d) {
return Math.abs(d.value.TOTAL) > 0.0001;
}
零点消失了:https://jsfiddle.net/3fovopxp/7/
我现在要修复常见问题解答...