我正在尝试删除空箱,或者我应该说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 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/

我将立即修复常见问题解答...

关于javascript - 无法从dc.js数据表中删除空容器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45041136/

10-16 21:24