Crossfilter查询

是否可以过滤具有数组值的交叉过滤数据集?

例如,假设我有以下数据集:

var data = [
  {
    bookname: "the joy of clojure",
    authors: ["Michael Fogus", "Chris Houser"],
    tags: ["clojure", "lisp"]
  },
  {
    bookname: "Eloquent Ruby",
    authors: ["Russ Olsen"],
    tags: ["ruby"]
  },
  {
    bookname: "Design Patterns in Ruby",
    authors: ["Russ Olsen"],
    tags: ["design patterns", "ruby"]
  }
];

有没有简单的方法来访问由特定标签标记的书籍? 还有那些有特定作者的书籍? 我理解如何使用crossfilter到目前为止,我做了这样的事情:

var filtered_data = crossfilter(data);
var tags = filtered_data.dimension(function(d) {return d.tags});
var tag = tags.group();

然后当我访问分组时(如此):

tag.all()

我得到这个:

[{key: ["clojure", "lisp"], value: 1}, 
 {key: ["design patterns", "ruby"], value: 1}, 
 {key: ["ruby"], value: 1}]

当我宁愿有这样的:

[{key: "ruby", value: 2}, 
 {key: "clojure", value: 1}, 
 {key: "lisp", value: 1},
 {key: "design patterns", value: 1}]

我在下面的代码中添加了评论。 大图:使用减少功能。

var data = ...
var filtered_data = crossfilter(data);
var tags = filtered_data.dimension(function(d) {return d.tags});

tags.groupAll().reduce(reduceAdd, reduceRemove, reduceInitial).value()

注意我如何使用groupAll()而不是group() b / c,我们希望我们的reduce函数(定义如下)在一个组上运行而不是3个组。

现在reduce函数应该是这样的:

/*
 v is the row in the dataset

 p is {} for the first execution (passed from reduceInitial). 
 For every subsequent execution it is the value returned from reduceAdd of the prev row
*/
function reduceAdd(p, v) {
  v.tags.forEach (function(val, idx) {
     p[val] = (p[val] || 0) + 1; //increment counts
  });
  return p;
}

function reduceRemove(p, v) {
   //omitted. not useful for demonstration
}

function reduceInitial() {
  /* this is how our reduce function is seeded. similar to how inject or fold 
   works in functional languages. this map will contain the final counts 
   by the time we are done reducing our entire data set.*/
  return {};  
}

我从未使用过“crossfilter”(我假设这是一个JS库)。 这里有一些纯粹的JS方法。

这个...

data.filter(function(d) {
  return d.authors.indexOf("Michael Fogus") !== -1;
})

返回这个:

[{bookname:"the joy of clojure", authors:["Michael Fogus", "Chris Houser"], tags:["clojure", "lisp"]}]

这个...

var res = {};
data.forEach(function(d) {
  d.tags.forEach(function(tag) {
    res.hasOwnProperty(tag) ? res[tag]++ : res[tag] = 1
  });
})

返回这个:

({clojure:1, lisp:1, ruby:2, 'design patterns':1})

对于其中的任何一种,您都可以应用d3.entries来获取您的{key:"ruby", value: 2}格式。

链接地址: http://www.djcxy.com/p/32745.html

上一篇: Crossfilter query

下一篇: DC.js stack in line chart not showing