问题
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.
Data looks like this:
Date , Labels
1/1/2015 , "A, B, C"
1/2/2015 , "B"
1/3/2015 , "C, A"
1/4/2015 , "A"
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.
回答1:
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.
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"
Working example: https://jsfiddle.net/z4k78odx/4/
来源:https://stackoverflow.com/questions/33828083/how-to-make-row-chart-for-multilabel-data-in-dc-js