简体   繁体   English

如何在dc.js中制作多标签数据的行图

[英]How to make row chart for multilabel data in 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. 我想使用dc.js制作一个折线图,绘制每个标签的出现次数。

Data looks like this: 数据如下所示:

Date , Labels 日期,标签
1/1/2015 , "A, B, C" 2015年1月1日,“ A,B,C”
1/2/2015 , "B" 2015年1月2日,“ B”
1/3/2015 , "C, A" 2015年1/3,“ C,A”
1/4/2015 , "A" 2015年1月4日,“ A”

I would like a row chart that aggregates them like this: 我想要一个这样汇总它们的行图:
A: 3 答:3
B: 2 B:2
C: 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. 任何帮助,将不胜感激。

You will need to use dimension.groupAll for this and manage the groupings on your own. 您将需要使用Dimension.groupAll并自行管理分组。 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? 但是,您是否看过Reductio,这使这一切变得容易? https://github.com/esjewett/reductio#groupall-aggregations 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//jsfiddle.net/z4k78odx/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM