Reputation: 884
I have this table structure:
Name Grade Count
X VeryGood 10
X Excellent 2
X Failed 0
Y VeryGood 7
Y Excellent 1
Y Failed 2
I want to show this data in stacked goole chart similar to this:
Horizontally: Count
Vertically: Name
Any ideas how can I achieve that? P.S: I am using ajax data source.
Upvotes: 1
Views: 190
Reputation: 61275
to draw the chart in question, the data table will need to be structured as follows,
with series / columns for each grade.
['Name', 'VeryGood', 'Excellent', 'Failed'],
['X', 10, 2, 0],
['Y', 7, 1, 2],
but this will be difficult to build,
without hard-coding the column values in the query.
instead, we can use google's DataView
and group
method.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Name', 'Grade', 'Count'],
['X', 'VeryGood', 10],
['X', 'Excellent', 2],
['X', 'Failed', 0],
['Y', 'VeryGood', 7],
['Y', 'Excellent', 1],
['Y', 'Failed', 2],
]);
var aggColumns = [];
var viewColumns = [0];
var distinctLabels = data.getDistinctValues(1);
distinctLabels.forEach(function (label, index) {
viewColumns.push({
calc: function (dt, row) {
if (dt.getValue(row, 1) === label) {
return dt.getValue(row, 2);
}
return null;
},
type: 'number',
label: label
});
aggColumns.push({
column: index + 1,
aggregation: google.visualization.data.sum,
type: 'number'
});
});
var view = new google.visualization.DataView(data);
view.setColumns(viewColumns);
var groupData = google.visualization.data.group(
view,
[0],
aggColumns
);
var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(groupData, {
isStacked: true
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
Upvotes: 1