c3.js generate a stacked bar from JSON payload

2019-09-12 05:38发布

问题:

I am attempting to generate a stacked bar chart with c3 when using a JSON payload (code below). However, when I group the data, instead of having a stacking behavior, they overlay instead. If I use the column structure, I get the intended behavior, but this means that I'd have different code generate for a stacked bar chart versus my other visuals (ie timeseries chart).

var chart = c3.generate({
data: {
    x: "x-axis",
    json:[
        { "x-axis": "0",
            "data1": 30
        },
        { "x-axis": "0",
            "data2": 40
        }],
        keys: {
            x: "x-axis",
            value: ["data1", "data2"]
        },
                groups: [
        ['data1', 'data2']
    ],
    type: 'bar'
}
});

Here is a fiddle: http://jsfiddle.net/cjrobinson/ozf4fzcb/

回答1:

It's weird they overplot each other in your example, I'd report that as a bug to c3

If you don't want to use the columns[] format, you could do it like below, would still need some data wrangling though:

var chart = c3.generate({
data: {
    x: "x-axis",
    json:[
        { "x-axis": "0",
            "data1": 30,
            "data2": 40
        },
        { "x-axis": "1",
            "data1" :20,
            "data2": 60
        }],
       // etc etc
        keys: {
            x: "x-axis",
            value: ["data1", "data2"]
        },
                groups: [
        ['data1', 'data2']
    ],
    type: 'bar'
}
});

http://jsfiddle.net/dhgujwy7/1/