dc.js和crossfilter堆栈条形图,包含已过滤和未过滤

时间:2014-04-02 03:36:03

标签: javascript d3.js crossfilter dc.js

我正在使用伟大的dc.js / d3.js / crossfilter组合 - 大多数都取得了巨大的成功。但是,我需要在过滤后的数据的同时保留未过滤的维度数据。我可以设置将未过滤的维度数据保存在对象中,然后访问它的方法,但是当使用这样一个强大的组合时,这似乎很弱。

具体来说,我正在尝试使用条形图底部的堆积条形图=未过滤的数字,条形图的顶部=过滤器的结果。如果我过滤,我找不到检索起始组计数的方法。

<input type="text" id = "keywordTxt"></input><button id = "filterButton">Filter</button>
<div id="i9chart"></div>   

var I9Chart = dc.barChart("#i9chart");
d3.csv("I9.csv",function(csv) {

  csv.forEach(function(d) {
    d.I9_Formatted = numberFormat(d.I9_Code);
    d.I9_Whole = Math.floor(d.I9_Code)
  })
//set up dimensions
  var ndx = crossfilter(csv);
  var I9_DescripDim = ndx.dimension(function(d) { return d.I9_Description; });
  var I9_WholeDim = ndx.dimension(function(d) { return d.I9_Whole; });
  var I9_WholeGroup = I9_WholeDim.group();
  var maxI9 = I9_WholeDim.top(1)[0].I9_Whole;
  var I10_DescripDim = ndx.dimension(function(d) { return d.I10_Description; });

  I9Chart.width(750)
    .height(300)
    .margins({top: 10, right: 20, bottom: 30, left: 40})
    .dimension(I9_WholeDim)
    .group(I9_WholeGroup)
// pretty much every approach I've tried results in the stack having the same y value as the filtered.
    .valueAccessor(function (d) {return d.value; })
    .stack(I9_WholeDim.group(),function(d,i) { return d.???; })
    .x(d3.scale.linear().domain([0,maxI9]))
    .rangeChart(ICD9ChartBrush)
    .brushOn(false)
    .title(function (d) { return d.key + ": " + d.value; })
    .elasticY(true)
    .centerBar(true);
//filter by the I10 description dimension
  document.getElementById("filterButton").onclick = function() {
    var keyword = document.getElementById("keywordTxt").value;
    var matcher = new RegExp(keyword,'i');
    var filteredDim = I10_DescripDim.filter(function(val, i){ return matcher.test(val)});

1 个答案:

答案 0 :(得分:2)

来自Ethan Jewett的刺激 - 解决我自己的问题:

将完整的,未经过滤的分组维度存储为静态对象(发现哈希效果最佳)
首先 - 在过滤之前抓取静态组

I9_WholeObjGroup = I9_WholeGroup.top(Infinity);

然后 - 更容易访问键和值:

var I9_hash = {};
I9_WholeObjGroup.forEach( function(p,i) {
    I9_hash[p.key] = p.value
})

最后,I9_hash用于堆栈函数(或其所需的任何其他位置)

.stack(I9_WholeGroup, "Total Items",function(d) { 
      if(d.value > 0 ){     //only add the stacked data to filtered bars that have data.
        var id = d.key
        return I9_hash[id] - d.value; //only add the difference between the filter and totals
       }
   })

堆栈的优点在于可以添加任何数字数据 - 常量,基于现有未过滤数据的变量,甚至是常量过滤数据(例如,对于堆积百分比图)