如何在dc.js中制作多标签数据的行图 [英] How to make row chart for multilabel data in dc.js
问题描述
我的数据只有一列,它是每个数据点的标签列表.我想使用dc.js制作一个折线图,绘制每个标签的出现次数.
I have data with one column that is a list of labels for each data point. I would like to use dc.js to make a row chart that plots the number of occurrences of each label.
数据如下:
日期,标签
2015年1月1日,"A,B,C"
2015年1月2日,"B"
2015年1/3,"C,A"
2015年1月4日,"A"
Date , Labels
1/1/2015 , "A, B, C"
1/2/2015 , "B"
1/3/2015 , "C, A"
1/4/2015 , "A"
我想要一个像这样汇总它们的行图:
答:3
B:2
C:2
I would like a row chart that aggregates them like this:
A: 3
B: 2
C: 2
到目前为止,我的代码:
My code so far:
var labels = ["A", "B", "C"];
var labelBar = dc.rowChart("#label-bar");
d3.csv('data.csv', function (csv) {
var data = crossfilter(csv);
var labelDim = data.dimension(function(d){return d["Labels"];});
var labelGroup = labelDim.group().reduce(
function(p,v) { //add
for (i = 0; i < labels.length; i++) {
if(v["Labels"].indexOf(labels[i]) > -1)
p[labels[i]]++;
}
return p;
},
function(p,v) { //subtract
for (i = 0; i < labels.length; i++) {
if(v["Labels"].indexOf(labels[i]) > -1)
p[labels[i]]--;
}
return p;
},
function(p,v) { //initial
p = {};
for (i = 0; i < labels.length; i++) {
p[labels[i]] = 0;
}
return p;
});
labelBar
.dimension(labelDim)
.group(labelGroup)
.elasticX(true);
});
该代码仅为每个数据点而不是每个标签创建一个带有一个条形图的折线图.任何帮助将不胜感激.
The code only creates a row chart with one bar for each data point, not for each label. Any help would be appreciated.
推荐答案
您将需要为此使用Dimension.groupAll并自行管理分组.如果您将一个实际的示例与您的尺寸放在一起,我可以向您展示如何做到这一点.
You will need to use dimension.groupAll for this and manage the groupings on your own. If you put together a working example with your dimension, I can show you how to do this.
但是,您是否看过Reductio,这使这变得非常容易? https://github.com/esjewett/reductio#groupall-aggregations
However, have you looked at Reductio, which makes this pretty easy? https://github.com/esjewett/reductio#groupall-aggregations
对于您的数据,您将执行类似的操作
With your data you would do something like
var dim = data.dimension(function(d) { return d.Labels.split(','); });
groupAll = dim.groupAll();
reducer = reductio()
.groupAll(function(record) {
return record.Labels.split(',');
})
.count(true);
reducer(groupAll);
groupAll.all(); // Should give you groups with keys "A", "B", "C"
工作示例: https://jsfiddle.net/z4k78odx/4/
这篇关于如何在dc.js中制作多标签数据的行图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!