Highcharts column drilldown - javascript

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: []
}
})
});

Related

how to get data from a jsonified page?

hi every one i have a function in flask that returns 2 jsonified lists. result & resultb and accessible on /dtt URI . ( return jsonify({'result': a}, {'resultb': b}) )
my problem is that when i am trying to use result or resultb i cannot use both of them. in function() i can not write function(result,resultb) and i should write on of them.
on getdata.done(function (result,resultb) when i remove result or resultb it works but i need both of them to make a chart!
$(document).ready(function() {
//--basic area echarts init-->
window.setInterval(function () {
var dom = document.getElementById("b-area1");
var myChart = echarts.init(dom);
var getdata= $.get('/dtt');
getdata.done(function (result,resultb) {
var app = {};
option = null;
option = {
color: ['#8dcaf3', '#67f3e4', '#4aa9e9'],
tooltip: {
trigger: 'axis'
},
legend: {
data: ['bits', 'KB']
},
calculable: true,
xAxis: [
{
type: 'category',
boundaryGap: false,
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Packets',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: result.result
},
{
name: 'KB',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: resultb.result
}
]
};
if (option && typeof option === "object") {
myChart.setOption(option, false);
}
});
},7300);
});
The done callback only returns one object ?
.done(function (response) {
console.log(response.result, response.resultb)
}
i have found the Problem ....
return jsonify({'result': a}, {'resultb': b})
this was wrong!!!
the correct form is:
return jsonify({'result': a, 'rs': b})
and then i could use response.rs or response.result on Jquery
there is some good things on this Link about my Problem :
How to return two arrays with jsonify in Flask?
Thank all...

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
},
]
});

Highcharts sort stacked bar

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); });
});
});

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 with JSON to customize multiple series

I would like to add multiple series in my graph from a json file with 4 columns (date, open incident, closed incident and in progress incident).
I can show my graph with the number of incident open (http://jsfiddle.net/269us/) but I can't find the 3rd and 4th columns of JSON file.
Here is the structure of my JSON file:
[[1325462400000,3,12,14]
[1325548800000,7,14,8]
[1325635200000,10,11,24]
[1325721600000,21,13,16]
[1325808000000,13,15,9]
[1325894400000,2,15,4]
[1326067200000,10,13,15]]
I want to reach as a result of this type in order to customize each series (open, closed, in progress)
var date = []
open = []
close = []
inprogress = []
datalength = data.length;
for (i = 0; i <dataLength; i + +) {
date.push ([
data [i] [0]
]);
open.push ([
data [i] [1],
]);
close.push ([
data [i] [2],
]);
inprogress.push ([
data [i] [3],
]);
}
series: [{
type: 'spline',
name: 'open',
data: open,
dataGrouping {
units: groupingUnits
}
} {
type: 'column',
name: 'close',
data: close,
dataGrouping {
units: groupingUnits
}
.............
.............
}]
I think you are trying to create 3 data arrays to use in 3 series (open, close and in-progress). Try something like this:
for (i = 0; i <dataLength; i + +) {
var date = data[i][0];
open.push ([
date,
data[i][1]
]);
close.push ([
data,data[i][2] //data instead of dat.
]);
inprogress.push ([
date,data[i][3]
]);
}
You sould now be able to use these 3 arrays as the data in your series:
series: [{
type: 'spline',
name: 'open',
data: open,
dataGrouping {
units: groupingUnits
}
},
{
type: 'column',
name: 'close',
data: close,
dataGrouping {
units: groupingUnits
}
},
{
type: 'line',
name: 'inprogress',
data: inprogess,
dataGrouping {
units: groupingUnits
}
}

Categories