1
votes

I am using google datavisualization charts. I have a datatable with 2 columns and 4 rows. I need to display this data into a single stacked bar chart as shown below
enter image description here

Sample of my data :

var data = new google.visualization.DataTable();
data.addColumn('string', 'name');
data.addColumn('number', 'count');
data.addRows([
    ['abc', 321],
    ['def', 163],
    ['ghi', 125],
    ['jkl', 197]
]);

I have tried using column chart and bar chart by enabling isStacked:true , but no luck. Is there a way to display the data in a single stacked chart as shown in the image. I don't mind whether it is a bar chart or column chart.

I would appreciate if someone can help me.

Thanks.

1

1 Answers

1
votes

The issue is that right now there is nothing linking the different columns together, so that there is no reason for them to be stacked on top of each other.

You need to have each of the elements share a common element, like the date. Next, you need to add a separate column for each of the different 'name' fields. Finally, when adding your values, add them only to the column index that matches the (name, value) pair.

data.addColumn('number', 'irrelevant');
data.addColumn('number', 'abc');
data.addColumn('number', 'def');
data.addColumn('number', 'ghi');
data.addColumn('number', 'jkl');
data.addColumn('number', 'mno');
data.addRows([
    [0, 321, 0, 0, 0, 0],
    [0, 0, 163, 0, 0, 0],
    [0, 0, 0, 125, 0, 0],
    [0, 0, 0, 0, 452, 0],
    [0, 0, 0, 0, 0, 825]
]);

This sort of thing is annoying to do by hand, so in my chart system I iterate through a list of all the different groupings (or 'name's in your case) and keep track of each index so I know which element of the individual row to specify.

Here's a small sample from my code so you can get the right idea:

GoogleDataTable.addColumn('number', 'Age');

var GroupIndex = 0;
var DateIndex = 0;

for (var i = 0; i < RawJSON.length; i++) {
    //If the groupkey is not in the group array yet.
    if (GroupArray.indexOf(RawJSON[i][GroupKey]) == -1) {
        GroupArray[GroupIndex] = RawJSON[i][GroupKey];
        GroupIndex++;
        GoogleDataTable.addColumn('number', RawJSON[i][GroupKey]);
    }
    //If the timeslice is not yet in the Date array.
    if (DateArray.indexOf(RawJSON[i]["Age"]) == -1) {
        DateArray[DateIndex] = RawJSON[i]['Age'];
        DateIndex++;
    }
}

then later

var groupIndex = GroupArray.indexOf(RawJSON[i][GroupKey]) + 1;
for (var j = 1; j <= GroupIndex; j++) {
    if (j == groupIndex) {
       RowArray[insertIndex][groupIndex] = RawJSON[i]['Value'];
    }
}