c3js中的数据聚合

Data aggregation in c3js

是否有聚合 C3 图表中数据的选项?当 JSON 包含具有相同类别的多个数据元素时,数据在图表中绘制为多个点,而在图表中它应该聚合并显示为单个点。 附件是 C3 图表和预期的图表格式。 在示例中: "name 1" 在 300 处显示单个点作为上传,其中离子 C3 在 200 处显示一个点,在 100 处显示另一个点。

使用的代码:

var chart = c3.generate({
            bindto:'#png-container',
            data: {
              json: [
                {name: 'name1', upload: 200, download: 200, total: 400},
                {name: 'name1', upload: 100, download: 300, total: 400},
                {name: 'name2', upload: 300, download: 200, total: 500},
                {name: 'name3', upload: 400, download: 100, total: 500},
              ],
              keys: {
                x: 'name', // it's possible to specify 'x' when category axis
                value: ['upload', 'download'],
              },
              groups: [
                ['name']
              ]
            },
            axis: {
              x: {
                type: 'category'
              }
            }
        });

以上代码的输出:

预期输出:

据我所知,c3 中没有内置。不过,您可以使用 d3 的嵌套运算符来聚合 json 数据,然后再将其传递给 c3。

var json = [
            {name: 'name1', upload: 200, download: 200, total: 400},
            {name: 'name1', upload: 100, download: 300, total: 400},
            {name: 'name2', upload: 300, download: 200, total: 500},
            {name: 'name3', upload: 400, download: 100, total: 500},
          ];

    var agg = function (json, nestField) {
        var nested_data = d3.nest()
            .key(function(d) { return d[nestField]; })
            .rollup(function(leaves) { 
                // Work out the fields we're not nesting by
                var keys = d3.merge (leaves.map (function(leaf) { return d3.keys(leaf); }));
                var keySet = d3.set(keys);
                keySet.remove (nestField);
                var dataFields = keySet.values();

                // total these fields up
                // console.log(leaves, dataFields); // just for testing
                var obj = {};
                dataFields.forEach (function (dfield) {
                    obj[dfield] = d3.sum(leaves, function(d) {return d[dfield];});
                });
                return obj; 
            })
            .entries(json);

        // return to original json format
        var final_data = nested_data.map (function(nestd) {
            nestd.values[nestField] = nestd.key;
            return nestd.values;
        });

        return final_data;
    };

    var chart = c3.generate({
        bindto:'#png-container',
        data: {
          json: agg(json, "name"),
          keys: {
            x: 'name', // it's possible to specify 'x' when category axis
            value: ['upload', 'download'],
          },
          groups: [
            ['name']
          ]
        },
        axis: {
          x: {
            type: 'category'
          }
        }
    });

https://jsfiddle.net/8uofn7pL/2/

哎呀,链接错了fiddle那里