user1735921 user1735921 - 26 days ago 5
Javascript Question

Convert cumulative chart to non-cumulative using highcharts

I want to convert a cumulative chart to a non-cumulative chart. Basically I have demo to show you:

This is the cumulative graph:
http://jsfiddle.net/h1qq1rj8/

And this is the non cumulative graph:
http://jsfiddle.net/h1qq1rj8/2/

$(function () {
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Total fruit consumtion, grouped by gender'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
yAxis: {
allowDecimals: false,
min: 0,
title: {
text: 'Number of fruits'
}
},
tooltip: {
formatter: function () {
return '<b>' + this.x + '</b><br/>' +
this.series.name + ': ' + this.y + '<br/>' +
'Total: ' + this.point.stackTotal;
}
},
plotOptions: {
column: {
stacking: 'normal'
}
},
series: [{
name: 'John',
data: [1, 8, 12, 13, 23], // I need to convert this data to non-cumulative
stack: 'male'
}]
});
});


I have cumulated data, to convert it into non cumulative I am subtracting data in the backend, but due to that I am getting slow performance, isn't there a option to make the chart non cumulative in highcharts API itself ?

Edit:

I have one more graph where data is formatted in different way:
http://jsfiddle.net/h1qq1rj8/3/

Answer

Highcharts will not do calculations on your data before drawing the chart, but you can move the calculation of this specific part from server-side to client side.

You can use the reduce function on the array to get the desired result:

old_ar = [1, 8, 12, 13, 23]
new_ar = old_ar.reduce(function(a, b, c, d) { if (a.length) {a.push(d[c]-d[c-1])} else {a = [b]} return a;}, [])
console.log(new_ar)

For the 2nd style of data you can use this:

old_ar = [[0,1],[1,8],[2,12],[3,13],[4,23]]
new_ar = old_ar.reduce(function(a, b, c, d) { if (a.length) {a.push([d[c][0], d[c][1]-d[c-1][1]])} else {a = [b]} return a;}, [])
console.log(new_ar)

Comments