Mantas Čekanauskas
Mantas Čekanauskas

Reputation: 2228

Kendo stacked bar chart categories

I got data in this Json format:

var demoData = [{
    Name: 'Category_1',
    Total: 100,
    Items: [{
        Name: 'Sub_Category_1_1',
        Total: 50
        }]
    },{
    Name: 'Category_2',
    Total: 20,
    Items: [{
        Name: 'Sub_Category_2_1',
        Total: 15
        },{
        Name: 'Sub_Category_2_2',
        Total: 45
    }]
}];

I use this data for kendo stacked bar chart, but first I parse to get a flat list:

for (var i = 0; i < data.length; i++) {
    for (var j = 0; j < data[i].Items.length; j++) {
        dataArray.push({
            name: data[i].Items[j].Name,
            stack: data[i].Name,
            data: [data[i].Items[j].Total]
        });
    }
}

Everything works, however, I would like to display category name under bars. But when I add

categoryAxis: {
    categories: catNames
}

where cats is array ['Category_1', 'Category_2', ....], it happens that all rendered bars get category named "Category_1" and "Category_2" and etc. have no bars above.

How should I configure kendo chart to display category names underneaths properly?

I have tried feeding data todataSource and grouping inside instead of using series, but I got similar result.

kendo dojo example

Upvotes: 0

Views: 2131

Answers (1)

flipside
flipside

Reputation: 81

Firstly, your data looks somewhat incorrect, you want your sub categories to repeat. Each category should contain all sub-categories ex:

var demoData = [{
Name: 'Category_1',
Total: 100,
Items: [{
    Name: 'Sub_Category_1',
  Total: 50
},{
    Name: 'Sub_Category_2',
  Total: 45
},{
    Name: 'Sub_Category_3',
  Total: 5
},{
    Name: 'Sub_Category_4',
  Total: null
}]
},{
Name: 'Category_2',
Total: 20,
Items: [{
    Name: 'Sub_Category_1',
  Total: 15
},{
    Name: 'Sub_Category_2',
  Total: 45
},{
    Name: 'Sub_Category_3',
  Total: null
},{
    Name: 'Sub_Category_4',
  Total: null
}]
},....

You also need to group your data by setting up a datasource:

var ds = new kendo.data.DataSource({
data: parsedData.seriesArray,
  group: {
    field: "name",
  },
  sort: [
    { field: "stack", dir: "asc" },
    { field: "name", dir: "asc" },
  ]
});

Now setup your series and categoryAxis:

dataSource: ds,
series: [{
    field: "data",
    stack: true,
}],
categoryAxis: {
  field: "stack",
},

And finally, you should not be adding your "data" field to an array in seriesArray:

data: data[i].Items[j].Total

dojo example

Upvotes: 1

Related Questions