操纵杆

时间:2015-07-30 20:39:16

标签: javascript d3.js

是的,所以这就是我的数据:

{
    "chartData":[
        {
            "vId":"307",
            "vNm":"Alejandro Rivera Ulloa",
            "values":[
                {"period":"2015-01","amount":37,"id":132},
                {"period":"2015-02","amount":38,"id":133},
                {"period":"2015-03","amount":33,"id":134}
            ]
        },
        {
            "vId":"308",
            "vNm": "Daniel Torres",
            "values": [
                {"period":"2015-01","amount":41,"id":135},
                {"period":"2015-02","amount":41,"id":136},
                {"period":"2015-03","amount":41,"id":137}
            ]
        },
        {
            "vId":"309",
            "vNm": "Pablo Alvarez Garcia",
            "values":[
                {"period":"2015-01","amount":16,"id":138},
                {"period":"2015-02","amount":17,"id":139},
                {"period":"2015-03","amount":14,"id":140}
            ],
        },
        {
            "vId":"391",
            "vNm":"Janette Avalos de Conte",
            "values":[
                {"period":"2015-01","amount":28.5,"id":141},
                {"period":"2015-02","amount":29,"id":142},
                {"period":"2015-03","amount":27.5,"id":143}
            ]
        }
    ]
}

现在,我想让这个图表(用不同的数据制作)的条形图是每个"值的总和"在数据中。  enter image description here

我没有编译数据本身内部的值的原因是因为这些相同的数据稍后将用于基于此数据的另一个图形。

所以,基本上。我的问题是:如何使条形成为每组"值的总和的高度"?

如果有人需要澄清,请发表评论。

我试图做一个d3.sum,但是这给了我一般的总和,并且迭代一系列总和并将每个总和推入一个数组并不是在D3中走在公园里。

1 个答案:

答案 0 :(得分:1)

以下函数按照您评论的方式聚合数据:

var cookData = function(data){
    var keys = {};
    var result = [];
    var values = data.map(function(d) { return d.values; });
    values.forEach(function (value){
        value.forEach(function (v) {
            if (keys[v.period]) {
                keys[v.period] += v.amount;    
            } else {
                keys[v.period] = v.amount;    
            }
        });
    })
    Object.keys(keys).forEach(function (key) {
        result.push({date: key, amount: keys[key]});
    });
    return result;
};

您可以使用条形图轻松使用此功能(有关如何创建条形图的示例,请参阅this。)