Sorting Stacked Bar Chart by Category Total
The default sorting in a stacked bar chart is by the Y-axis values. But you can sort your stacked bar chart by the total value of the categories instead.
- To do this, apply the following code snippet on the widget level:
widget.on('processresult',function(s,e){
//////////////////////////
// Sort the categories //
//////////////////////////
// User defined sort order
var sortOrder = "desc"; // Can be 'asc' for ascending order or 'desc' for descending order
// Get the categories
var categories = e.result.xAxis.categories;
// Create array to hold the totals
var totals = [];
// Get the data
var data = e.result.series;
// Loop through each category
for (var i=0; i<categories.length; i++){
// Init a variable to hold to total for the category
var total = 0;
// Loop through each value within the category, to calculate the total
for (var j=0; j<data.length; j++) {
total += data[j].data[i].y;
}
// Loop through each value within the category, to save the total
for (var j=0; j<data.length; j++) {
data[j].data[i].total = total;
}
// Save the total of the category
totals[i] = {
total: total,
originalIndex: i,
name: categories[i]
}
}
// Function to sort the list of categories ascending
function sortAsc(a,b) {
if (a.total < b.total)
return -1;
if (a.total > b.total)
return 1;
return 0;
}
// Function to sort the list of categories descending
function sortDesc(a,b) {
if (a.total < b.total)
return 1;
if (a.total > b.total)
return -1;
return 0;
}
// Run the function to sort the categories based on total values
if (sortOrder == "asc") {
totals.sort(sortAsc);
} else {
totals.sort(sortDesc);
}
// Loop through the new sorted Categories and make sure the x-axis matches
for (var k=0; k<totals.length; k++){
// Overwrite the old category name
e.result.xAxis.categories[k] = totals[k].name;
}
// Loop through each data series and sort the values
for (var l=0; l<data.length; l++){
if (sortOrder == "asc") {
data[l].data.sort(sortAsc);
} else {
data[l].data.sort(sortDesc);
}
}
})
- If needed, modify the sorting order in this parameter:
var sortOrder
By default, values are sorted in descending order.
Before the script has been applied:
After the script has been applied:
-
Hey Liz,
Not sure if you are aware of this plugin, but this sorts both the category and the break by and let's you display the totals on the chart as well:
Best, Elliott
Please sign in to leave a comment.
Comments
1 comment