Search code examples
c3

Specifying "groups" dynamically in stacked bar chart c3js


//take this code as an example

Here i have specified yvalue[0],yvalue[1] in groups.. But i need a general design ,where I dont know the number of groups that i have to create(i.e the number of segments) this varies according to the json data.

Consider this example here I have total,total1 therefore i have only 2 values.But if a third variable say total2 is specified in json, I should have a segment for it in my bar chart and so on.This has to be done without altering the groups everytime a field is added.Is there any way to achieve this??

Thanks

var datajson = [ {
country : "china",
total : 20,
total1 : 10
}, {
country : "India",
total : 40,
total1 : 20
}, {
country : "aus",
total : 10,
total1 : 30
}, {
country : "nxz",
total : 50,
total1 : 40
}

    ];

    var xvalue;
    var yvalue = [];
    var i = 0;

    var obj = datajson[0]
    for ( var key in obj) {
        if (xvalue === undefined)
            xvalue = key;
        else {
            yvalue[i] = key;
            i++;
        }

    }



    var chart = c3.generate({
        bindto : '#chart',
        data : {
            json : datajson,

            type : 'bar',
            keys : {
                x : xvalue, // it's possible to specify 'x' when category axis
                value : [yvalue[0],yvalue[1]],
            },
            groups : [ [yvalue[0],yvalue[1]] ]
        },
        bar : {
            width : {
                ratio : 0.3
            // this makes bar width 50% of length between ticks
            }
        },
        axis : {
            x : {
                type : 'category'

        },


        }
    });

Solution

  • Your question seems to have most of the answer (you are already generating the yvalue array from the object properties).

    You just don't have to specify the elements one by one, instead you can just pass in the array directly and you are done.

    groups: [yvalue]