Highcharts sort stacked bar - javascript

I didn't see any solutions matching the exact scenario I was hitting in Highcharts so I'm posting my find here.
I have a stacked bar chart in Highcharts and needed the bars to be sorted by value greatest to smallest and maintain their category relationship. Normally the preferred solution would be to sort the data before sending it in to Highcharts but that wasn't an option in my scenario.
Credit to the original poster where I found the solution here

You should perform the Chart.redraw() only once after all setData operations are finished: http://jsfiddle.net/BlackLabel/2mLg7235/
$.each(series, function(seriesIndex, ser) {
(...)
ser.setData(data, false);
});
chartSource.redraw();
In your code the redraw happens after every setData operation.
In my example the sorting function executes two times faster or so (thanks to this modification).

This solution is slow to execute as it post-processes the chart data. If I find a way to speed it up, I will update the code posted here.
http://jsfiddle.net/eecvsj7s/
$(function () {
var chart;
var sortData = function(chartSource) {
var series = chartSource.series;
var axis = chartSource.xAxis[0];
var categories = [];
if($.isArray(series)) {
var ser = $.grep(series, function(ser, seriesIndex) {
return ser.visible;
})[0];
$.each(ser.data, function(dataIndex, datum) {
console.log(datum.category + ": " + datum.stackTotal);
var obj = {
name: datum.category,
index: dataIndex,
stackTotal: datum.stackTotal
}
categories.push(obj);
});
}
categories.sort(function(a, b) {
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
var aTotal = a.stackTotal;
var bTotal = b.stackTotal;
if(aTotal === bTotal) {
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
} else {
return ((aTotal > bTotal) ? -1 : ((aTotal < bTotal) ? 1 : 0));
}
});
var mappedIndex = $.map(categories, function(category, index) {
return category.index;
});
categories = $.map(categories, function(category, index) {
return category.name;
});
console.log(categories);
console.log(mappedIndex);
axis.setCategories(categories);
$.each(series, function(seriesIndex, ser) {
var data = $.map(mappedIndex, function(mappedIndex, origIndex) {
return ser.data[mappedIndex].y;
});
ser.setData(data,false);
});
chartSource.redraw();
};
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: 'Stacked column chart'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
yAxis: {
min: 0,
title: {
text: 'Total fruit consumption'
}
},
plotOptions: {
series: {
stacking: 'normal',
events: {
hide: function() { sortData(chart); },
show: function() { sortData(chart); }
}
}
},
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
}, function(chart) { sortData(chart); });
});
});

Related

Calling Typescript function from Highcharts load event

I am trying to call typescript function openDialog() from the events.load of highcharts but I am not able to call it. Even though I am using arrow function I am not able to get it. Here is my code :
events: {
load: () => {
var chart : any = this;
for (var j in chart.series) {
var series = chart.series[j];
for (var i in series.data) {
((i) =>{
var point = series.data[i];
if (point.graphic) {
point.graphic.on('click',(e)=>this.openDialog(point.options,'all')
);
}
})(i)
}
}
}
},
public openDialog(option,type){
//Do Something
}
EDIT
I have got one link where there are binding this with function.
Is there anything that I am missing ?
Check the update code replacing arrow function,
Here assigning chart options has moved to a function, init(){} and declared var that = this; inside it, also replaced the ()=>{} with function().
You can check the stackblitz update Here
import { Component, OnInit, ElementRef, ViewChild} from '#angular/core';
import { Chart } from 'angular-highcharts';
import { HighchartsService } from './highcharts.service.ts'
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
#ViewChild('charts') public chartEl: ElementRef;
myOptions={};
constructor(private highcharts: HighchartsService) { }
ngOnInit(){
this.init();
this.highcharts.createChart(this.chartEl.nativeElement, this.myOptions);
}
init(){
var that = this;
this.myOptions = {
chart: {
type: 'bar',
events: {
load: function(){
var chart : any = this;
for (var j in chart.series) {
var series = chart.series[j];
for (var i in series.data) {
((i) =>{
var point = series.data[i];
if (point.graphic) {
point.graphic.on('click',(e)=>that.openDialog()
);
}
})(i)
}
}
}
},
},
title: {
text: 'Stacked bar chart'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
yAxis: {
min: 0,
title: {
text: 'Total fruit consumption'
}
},
legend: {
reversed: true
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
};
}
public openDialog(){
console.log('open dialog, hey this works here')
}
}
I am not sure this will work or not, but from my understanding, your this is not pointing to myOptions object and series key is present in myOptions object,
To make this work you should declare series outside of myOptions object
seriesData = [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}];
myOptions = {
chart: {
type: 'bar',
events: {
load: () => {
for (var j in this.seriesData) {
var series = this.seriesData[j];
for (var i in series.data) {
.
.
}
}
}
}
},
series: this.seriesData
}
Finally got it worked by this simple change
events: {
load: function(e) {
var chart : any = e.target; // to get the chart details
for (var j in chart.series) {
console.log(j)
var series = chart.series[j];
for (var i in series.data) {
((i) =>{
console.log(i)
var point = series.data[i];
if (point.graphic) {
point.graphic.on('click',(e)=>this.openDialog()
);
}
})(i)
}
}
}.bind(this) //binding the parent this to access openDialog function
},
public openDialog(option,type){
//Do Something
}
Here I had to bind this which does not comes from chart. So I have to bind this using .bint(this) to the load function. And to get the chart details I am using e.target. This way I am getting it worked.
Stackblitz Demo

highcharts doesn't read data, works with fake data

I'm trying to make visualization of the voltage, Array has 1k elements but I'm testing it on first 10 for now, the thing is that It doesn't display anything, what's more interesting when I use fake date which is commented out now, It shows chart properly. I thought that perhaps there is some problem with array so tried to use Array.from but it also brought no effect, here is my code:
.then(function(res) {
var averageVoltage = []
var inputVoltage = []
var date = []
for (var i = 0; i < 10; i++) {
if (res[i].average_volatage !== undefined) {
averageVoltage.push(res[i].average_volatage)
date.push(res[i].timestamp)
}
}
console.log(averageVoltage)
console.log(date)
Highcharts.chart('battery_chart', {
chart: {
type: 'line'
},
title: {
text: id
},
yAxis: {
title: {
text: 'Measurement'
},
},
xAxis: {
categories: date
},
series: [{
name: 'Average Voltage',
data: averageVoltage
// data: [12283, 12283, 12281, 12280, 12282, 12283, 12281, 12282, 12281, 12280]
},
]
});
and that's how array is shown in console.log:
Your array should show up as [12283, 12281, 12280, etc.] in console as well, instead it shows up as [Number, Number, ...]. Try changing this line:
averageVoltage.push(res[i].average_volatage)
to:
averageVoltage.push(parseInt(res[i].average_volatage))
Additionally, instead of using dates as categories, it could be easier to use the highchart datetime axis. This would let you manipulate how you want the date displayed, have several series with different timestamps in one graph, and many other things. To get this to work, you could do this:
.then(function(res) {
var averageVoltage = []
var inputVoltage = []
for (var i = 0; i < 10; i++) {
if (res[i].average_volatage !== undefined) {
averageVoltage.push({x: new Date(res[i].timestamp).getTime(), y: parseInt(res[i].average_volatage)})
}
}
console.log(averageVoltage)
Highcharts.chart('battery_chart', {
chart: {
type: 'line'
},
title: {
text: id
},
yAxis: {
title: {
text: 'Measurement'
},
},
xAxis: {
type: 'datetime'
},
series: [{
name: 'Average Voltage',
data: averageVoltage
},
]
});

making large csv chartable by querying iso code in highcharts

I'm trying to load a csv and format it so it will display as a chart in highcharts, this is proving difficult because of the structure of the csv data.
Here is the csv: https://pastebin.com/Ynz7GJJh
Sample:
iso,type,year,affected
JAM,Earthquake,1907,90000
JAM,Storm,1912,94820
TON,Volcano,1946,2500
DZA,Earthquake,1954,129250
HTI,Storm,1954,250000
Here is my highcharts.ajax so far
var hsOptions = {
chart: {
type: 'column'
},
title: {
text: 'KEY NATURAL HAZARD STATISTICS'
},
subtitle: {
text: 'Number of People Affected'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units'
}
},
series: []
};
Highcharts.ajax({
url: '/pathto.csv',
dataType: 'text',
success: function(csv) {
var rows = csv.split(/\r\n|\n/);
var cell;
var series = [];
var seriesBuilder = {name: countryValue, data: []};
for (var i = 0; i < rows.length; i++) {
cell = rows[i].split(',');
if (cell[0] === countryValue){
seriesBuilder.data.push(cell);
}
}
console.log(seriesBuilder);
series.push(seriesBuilder);
hsOptions.series.push(series);
Highcharts.chart('hazard-stats', hsOptions);
},
error: function (e, t) {
console.error(e, t);
}
});
which does make this
But I need this to build a series per disaster type, then the years have to combine on their own axis... it should be able to render just like this:

Javascript HighCharts reading from a different format

I am using Highcharts and i currently have 2 arrays which I would like to stop reading from and start reading the data from my object.
Here is the code i currently have:
items = ['Item 1', 'Item 2'];
Quantity = [10 , 5];
jQuery('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
categories: mydata
},
title: {
text: 'Items Title'
},
series: [{
name: 'Items',
data: Quantity
}],
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}<br/>',
shared: true
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function () {
console.log('Clicked');
},
},
},
},
},
});
The above displays 2 items of height 10 and 5.
Now what I need to do is to be able to read this data instead:
var mydata = {
"items":[{
"id":"123",
"name":"item name here",
"subitems":[{
"id":"567",
"name":"subitem 1"
},
{
"id":"657",
"name":"subitem 2"
}],
"somthing here":null,
},
{
"id":"456",
"name":"item name here too",
"subitems":[{
"id":"567",
"name":"subitem here"
},
{
"id":"657",
"name":"subitem here roo"
}],
"somthing here":null,
}]
};
The quantity values need to be the subitems count so in the case of the data above it would be 2,2
How can I do this?
This should get you started:
https://jsfiddle.net/b3wii/0Lx77f1a
If you click on a column it reads the mydata and displays the subitems. To get the subItem count just use mydata.items[i]['subitems'].length. To update the existing Item values change currentItemY or currentItemX.
click: function (e) {
if(this.series.name != 'SubItems'){
let currentItemName = items[this.index];
let currentItemY = this.y;
let currentItemX = this.x;
let newCategories = [];
let newSeries = [];
for(let i in mydata.items){
if(mydata.items[i]['name'] == currentItemName){
for(let j in mydata.items[i]['subitems']){
newCategories.push(mydata.items[i]['subitems'][j]['name']);
newSeries.push(mydata.items[i]['subitems'][j]['quantity']);
}
}
}
chart.update({
xAxis: {
categories: newCategories
},
series: [{
name: 'SubItems',
data: newSeries
}]
});
}
},

Highcharts column drilldown

From my php file, my array prints something this:
Array
(
[2011] => Array
(
[name] => 2011
[total] => 963
[drilldown] => true
)
[2012] => Array
(
[name] => 2012
[total] => 1997
[drilldown] => true
)
[2013] => Array
(
[name] => 2013
[total] => 1188
[drilldown] => true
)
)
And this is the json_encode:
{"2011":{"name":2011,"total":963,"drilldown":"true"},
"2012":{"name":2012,"total":1997,"drilldown":"true"},
"2013":{"name":2013,"total":1188,"drilldown":"true"}}
from this working link: highcharts/drilldown
data: [{
name: 'Animals',
y: 5,
drilldown: true
}, {
name: 'Fruits',
y: 2,
drilldown: true
}, {
name: 'Cars',
y: 4,
drilldown: true
}]
I want to change this part with my json.
I have made a JSFIDDLE demo.
What you need to do is assign the json encoded string of PHP array to a javascript variable like this:
var my_data = <?php echo json_encode($php_array); ?>
on this the variable my_data will have values like:
var my_data = {
"2011":{"name":2011,"total":963,"drilldown":"true"},
"2012":{"name":2012,"total":1997,"drilldown":"true"},
"2013":{"name":2013,"total":1188,"drilldown":"true"}
};
now this object needs to be structured into the format so that highcharts can use it as data source for plotting the values for the graph. It can be done like this:
var data_array = [];
$.each(my_data, function(key, value){
var total_value = value.total;
delete value.total;//remove the attribute total
value.y = total_value;//add a new attribute "y" for plotting values on y-axis
data_array.push(value);
});
after this data_array will have structure like:
data_array = [
{"name":2011,"y":963,"drilldown":"true"},//note we have removed attribute "total" with "y"
{"name":2012,"y":1997,"drilldown":"true"},
{"name":2013,"y":1188,"drilldown":"true"}
];
and now this data_array can be passed as data source to the chart while initialization like this:
// Create the chart
$('#container').highcharts({
....
.....
series: [{
name: 'Things',
colorByPoint: true,
data:data_array//put the data_array here
....
..
and you are done !
Here is the complete code:
$(function () {
var data_array = [];
//assign the json encoded string of PHP array here like:
//var my_data = <?php echo json_encode($php_array); ?>
var my_data = {
"2011":{"name":2011,"total":963,"drilldown":"true"},
"2012":{"name":2012,"total":1997,"drilldown":"true"},
"2013":{"name":2013,"total":1188,"drilldown":"true"}
};
$.each(my_data, function(key, value){
//console.log("key = "+key);
//console.log("value=");
//console.log(value);
var total_value = value.total;
delete value.total;//remove the attribute total
value.y = total_value;//add a new attribute "y" for plotting values on y-axis
data_array.push(value);
});
//console.log("data_array = ");
//console.log(data_array);
// Create the chart
$('#container').highcharts({
chart: {
type: 'column',
events: {
drilldown: function (e) {
if (!e.seriesOptions) {
var chart = this,
drilldowns = {
'Animals': {
name: 'Animals',
data: [
['Cows', 2],
['Sheep', 3]
]
},
'Fruits': {
name: 'Fruits',
data: [
['Apples', 5],
['Oranges', 7],
['Bananas', 2]
]
},
'Cars': {
name: 'Cars',
data: [
['Toyota', 1],
['Volkswagen', 2],
['Opel', 5]
]
}
},
series = drilldowns[e.point.name];
// Show the loading label
chart.showLoading('Simulating Ajax ...');
setTimeout(function () {
chart.hideLoading();
chart.addSeriesAsDrilldown(e.point, series);
}, 1000);
}
}
}
},
title: {
text: 'Async drilldown'
},
xAxis: {
type: 'category'
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
}
}
},
series: [{
name: 'Things',
colorByPoint: true,
data:data_array
}],
drilldown: {
series: []
}
})
});

Categories