gpt4 book ai didi

javascript - 有没有办法告诉 crossfilter 将数组元素视为单独的记录,而不是将整个数组视为单个键?

转载 作者:IT王子 更新时间:2023-10-29 03:11:05 24 4
gpt4 key购买 nike

我有一些字段值是数组的数据集,我想使用 crossfilter 和 d3.js 或 dc.js 来显示每个值在数据集中出现的次数的直方图。

这是一个例子:

var data = [
{"key":"KEY-1","tags":["tag1", "tag2"]},
{"key":"KEY-2","tags":["tag2"]},
{"key":"KEY-3","tags":["tag3", "tag1"]}];

var cf = crossfilter(data);

var tags = cf.dimension(function(d){ return d.tags;});
var tagsGroup = tags.group();


dc.rowChart("#chart")
.renderLabel(true)
.dimension(tags)
.group(tagsGroup)
.xAxis().ticks(3);

dc.renderAll();

和 JSFiddle http://jsfiddle.net/uhXf5/2/

当我运行该代码时,它会生成如下图:

graph1

但我想要的是这样的:

enter image description here

为了让事情变得更加复杂,如果能够点击任何行并通过点击的标签过滤数据集,那就太棒了。

有人知道如何实现吗?

谢谢,科斯佳

最佳答案

我自己解决了,这里是工作代码 http://jsfiddle.net/uhXf5/6/

下面是代码,以防有人遇到类似问题:

function reduceAdd(p, v) {
v.tags.forEach (function(val, idx) {
p[val] = (p[val] || 0) + 1; //increment counts
});
return p;
}

function reduceRemove(p, v) {
v.tags.forEach (function(val, idx) {
p[val] = (p[val] || 0) - 1; //decrement counts
});
return p;

}

function reduceInitial() {
return {};
}


var data = [
{"key":"KEY-1","tags":["tag1", "tag2"], "date":new Date("10/02/2012")},
{"key":"KEY-2","tags":["tag2"], "date": new Date("10/05/2012")},
{"key":"KEY-3","tags":["tag3", "tag1"], "date":new Date("10/08/2012")}];

var cf = crossfilter(data);

var tags = cf.dimension(function(d){ return d.tags;});
var tagsGroup = tags.groupAll().reduce(reduceAdd, reduceRemove, reduceInitial).value();
// hack to make dc.js charts work
tagsGroup.all = function() {
var newObject = [];
for (var key in this) {
if (this.hasOwnProperty(key) && key != "all") {
newObject.push({
key: key,
value: this[key]
});
}
}
return newObject;
}


var dates = cf.dimension(function(d){ return d.date;});
var datesGroup = dates.group();


var chart = dc.rowChart("#chart");
chart
.renderLabel(true)
.dimension(tags)
.group(tagsGroup)
.filterHandler(function(dimension, filter){
dimension.filter(function(d) {return chart.filter() != null ? d.indexOf(chart.filter()) >= 0 : true;}); // perform filtering
return filter; // return the actual filter value
})
.xAxis().ticks(3);

var chart2 = dc.barChart("#chart2");
chart2
.width(500)
.transitionDuration(800)
.margins({top: 10, right: 50, bottom: 30, left: 40})
.dimension(dates)
.group(datesGroup)
.elasticY(true)
.elasticX(true)
.round(d3.time.day.round)
.x(d3.time.scale())
.xUnits(d3.time.days)
.centerBar(true)
.renderHorizontalGridLines(true)
.brushOn(true);


dc.renderAll();

关于javascript - 有没有办法告诉 crossfilter 将数组元素视为单独的记录,而不是将整个数组视为单个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17524627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com