Highcharts to populate data for pie chart using json object - highcharts

hi my json object looks like this
[
{"name":"Tokyo","data":3.0},
{"name":"NewYork","data":2.0},
{"name":"Berlin","data":3.5},
{"name":"London","data":1.5}
]
How to populate the series points to make a pie chart using highcharts

Try this below code. This will parse all the values and create an array called dataArrayFinal .
var d = [{"name":"Tokyo","data":3.0},{"name":"NewYork","data":2.0}, {"name":"Berlin","data":3.5},{"name":"London","data":1.5}]
var name = Array();
var data = Array();
var dataArrayFinal = Array();
for(i=0;i<d.length;i++) {
name[i] = d[i].name;
data[i] = d[i].data;
}
for(j=0;j<name.length;j++) {
var temp = new Array(name[j],data[j]);
dataArrayFinal[j] = temp;
}
And your series stuff should look like below. i.e, you should pass the array dataArrayFinal like below.
series: [{
type: 'pie',
name: 'Browser share',
data: dataArrayFinal
}]

Actually the only difference between your data definition and the format that Highcharts requires, is that yours has a property called "data" where Highcharts expects "y". So you just need to loop over the data and set that property. See it live at http://jsfiddle.net/highcharts/uTyZk/.
// Original data
var data = [{
"name": "Tokyo",
"data": 3.0
}, {
"name": "NewYork",
"data": 2.0
}, {
"name": "Berlin",
"data": 3.5
}, {
"name": "London",
"data": 1.5
}];
// Highcharts requires the y option to be set
$.each(data, function (i, point) {
point.y = point.data;
});
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie'
},
series: [{
data: data
}]
});

Related

Convert and Sort Data for HighChart Column Range Representation

I have some data coming in random order and would like to convert into into a specific order for Highchart column ranges. Any insight on doing this effectively and insight would help
Also regardless of order of input data I always want to show chart in Apple Orange Banana order with their correct representation
I have tried using maps,sets,array in ruby and have something working which is super brittle and not the most effective.
headers = Array.wrap(raw_data.dig('data', 'dimensions', 'axes', 'headers'))
values = Array.wrap(raw_data.dig('data', 'values', 'c')).map(&:to_f)
labels = headers.map { |header| Array.wrap(header['label']) }
data = values.each_slice(2)
This is the weight of the fruits LOW is lowest weight and HIGH is highest weight. The problem is order of data is ordered by weight so I cant just slice consecutive values of array.
JSON DATA
{
"data": {
"dimensions": {
"axes": {
"headers": [{
"label": ["Apple", "Low"]
}, {
"label": ["Apple", "High"]
}, {
"label": ["Orange", "Low"]
}, {
"label": ["Banana", "Low"]
}, {
"label": ["Orange", "High"]
}, {
"label": ["Banana", "High"]
}]
}
}
"values": {
"c": ["173", "273", "414", "608", "610", "1050"]
}
}
EXPECTED OUTPUT
{
series: [
{'name': 'Weight', 'data': [[173, 273], [414, 610], [608, 1050]]}
],
axis_labels: ['Apple', 'Orange', 'Banana'],
}
chart
https://jsfiddle.net/Praveen2710/7sdqz6Le/8/
You need to preprocess your data to the format required by Highcharts:
var json = {...}
var series = {
name: 'Weight',
data: []
},
i,
header1,
header2,
value,
indexOf,
point,
categories = [];
for (i = 0; i < json.data.values.c.length; i++) {
labels = json.data.dimensions.axes.headers[i].label;
header1 = labels[0].toLowerCase(),
header2 = labels[1].toLowerCase(),
value = json.data.values.c[i];
indexOf = categories.indexOf(header1);
if (indexOf !== -1) {
series.data[indexOf][header2] = Number(value);
} else {
categories.push(header1);
series.data.push({
[header2]: Number(value),
x: series.data.length
});
}
}
Highcharts.chart('container', {
...,
series: [series]
});
Live demo: http://jsfiddle.net/BlackLabel/nm976qho/

Highcharts more than one series

I have a simple json document :
[ {
"x" : "a",
"y" : 2
}, {
"x" : "b",
"y" : 8
}, {
"x" : "c",
"y" : 4
}, {
"x" : "d",
"y" : 15
} ]
I want to visualize it using Highcharts having 4 series. I could success, however, the data appeared only as one series (see the next Figure).
Here is part of the code:
var options = {
.
.
.
series: [{ }]
};
.
.
.
var data = JSON.parse(json);
var seriesData = [];
for (var i = 0; i < data.length; i++) {
seriesData.push([data[i].x, data[i].y]);
options.xAxis.categories.push( data[i].x );
}
options.series[0].data = seriesData;
var chart = new Highcharts.Chart(options);
also updating the series
chart.series[0].update({
type: type,
});
works fine.
using
options.series.push({name: data[i].x, data: [data[i].x, data[i].y]});
creates 4 series but not appropriately visualized and also updating the series
chart.series[0].update({
type: type,
});
doesn't work, therefore, I want to focus in the first mentioned method.
any hints?
EDit: code which partially works for me:
var options = {
chart: {
renderTo: 'container',
type: 'column' //default
},
title: {
text: ''
},
yAxis: {
title: {
enabled: true,
text: 'Count',
style: {
fontWeight: 'normal'
}
}
},
xAxis: {
title: {
enabled: true,
text: '',
style: {
fontWeight: 'normal'
}
},
categories: [],
crosshair: true
} ,
plotOptions: {
pie: {
innerSize: 125,
depth: 80
},
column: {
pointPadding: 0.2,
borderWidth: 0,
grouping: false
}
},
series: [{ }]
};
// Set type
$.each(['column', 'pie'], function (i, type) {
$('#' + type).click(function () {
chart.series[0].update({
type: type
});
});
var data = get the data fom json file**
var seriesData = [];
for (var i = 0; i < data.length; i++) {
seriesData.push([data[i].x, data[i].y]);
options.xAxis.categories.push( data[i].x );
}
options.series[0].data = seriesData;
var chart = new Highcharts.Chart(options);
});
});
You have to decide whether you want to have 4 different series and update all 4 series at once or you want to have one series an then build e.g. legend on your own.
If you want to have 4 series, set grouping to false, set xAxis categories and each point should be mapped to one series with one point - the point.x should have the index of the series.
const series = data.map((point, x) => ({ name: point.x, data: [{ x, y: point.y }]}))
const chart = Highcharts.chart('container', {
chart: {
type: 'column'
},
plotOptions: {
column: {
grouping: false
}
},
xAxis: {
categories: data.map(point => point.x)
},
series: series
});
Then you can update your all 4 series:
chart.series.forEach(series => series.update({
type: series.type === 'column' ? 'scatter' : 'column'
}, false))
chart.redraw()
example: http://jsfiddle.net/pdjqrj5y/

Parsing ALL Highcharts Options from JSON

I am currently wanting to specify all Highcharts chart options via a JSON file. I've seen plenty of examples on how to pull just the data series from JSON and understand that.
Here is an example of some chart options that I would like to convert to JSON
var optionsChart2 = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Year End Rating: Distribution'
},
xAxis: {
categories: [
'Ineffective',
'Inconsistent',
'Proficient',
'Advanced',
'Exceptional'
]
},
yAxis: {
min: 0,
title: {
text: 'Percentage'
}
},
series: [{data: 25,50,65,32,78}]
};
What is the best JSON format for that (for the purpose of pulling in via AJAX and then parsing back into options)?
I've seen the following code for parsing just the data:
$.getJSON('data.json', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
How would I then use the new version of the JSON file (as above)?
I'm sorry if this is too vague. I'm relatively new to this and need some help!
Well, it should be valid json, not valid javascript.
So strip the var and start immediately with the opening brace, remove the ; at the end and add double quotes around each property name.
So it looks like this:
{
"chart" : { ...
...
}
Then do the same as your example, just pass the response as is to the HC constructor:
$.getJSON( 'options.json', function( options ) {
new Highcharts.Chart(options);
});

Highstock Issue - Can't draw and plot chart correctly

I'm working on project to display stock information using Highstock.
Question 1:
I tried to display ohlc data using ohlc graph, high and low using areasplinerange graph, and volume using column chart.
Everything works fine, if i zoom 1m, 3m, 6m, YTD, and 1y. Here is the snapshot. link1. But if zoom to All, The graph messed up like this link2.
Am i wrong in my coding or it's bug?
Question 2:
In the same chart, I have code to change the type of graph from ohlc to line. It works fine when I zoom to 1m, 3m. Here is the snapshot link3. But it show me no line chart when i zoom to 6m, 1y, and All. Here is the snapshot link4.
How can this happen?
Thank you for your help.
The Code:
Here is the code that i used to display the chart
$.getJSON(url, function (data1) {
$.getJSON(urlprediction, function (data2) {
var ohlc = [],
volume = [],
closed = [],
forecast = [],
dataLength1 = data1.length;
dataLength2 = data2.length;
for (i = 0; i < dataLength1; i++) {
ohlc.push([
data1[i][0], // the date
data1[i][1], // open
data1[i][2], // high
data1[i][3], // low
data1[i][4] // close
]);
closed.push([
data1[i][0], // the date
data1[i][4] // close
]);
volume.push([
data1[i][0], // the date
data1[i][5] // the volume
])
}
for (i = 0; i < dataLength2; i++) {
forecast.push([
data1[i][0], // the date
data1[i][1],
data1[i][2], // close
])
}
// set the allowed units for data grouping
var groupingUnits = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: title
},
yAxis: [{
title: {
text: 'OHLC'
},
height: 360,
lineWidth: 2
}, {
title: {
text: 'Volume'
},
top: 433,
height: 100,
offset: 0,
lineWidth: 2
}],
series: [{
type: 'ohlc',
name: stockname,
data: ohlc,
}, {
type: 'areasplinerange',
name: stockname,
data: data2,
}, {
type: 'column',
name: 'Volume',
data: volume,
yAxis: 1,
}]
});
});
});

Unexpected Highcharts results

I'm using highcharts as shown in examples but for some reason it flat out does not like my data. The only time I see a result is when I zoom out to all and then it only shows one point. Any clues as to what I'm doing wrong would be extremely appreciated.
how im getting my data:
$jsResult = array();
$arResults = $wpdb->get_results("SELECT tsDay, nPrice FROM sometable", ARRAY_A);
foreach($arResults as $key => $val){
//$val['nPrice'] = floatval($val['nPrice']);
//$jsResult[$key][0] = ($val['tsDay']*1000);
//$jsResult[$key][1] = intval($val['nPrice']);
//$strDate = date("Y/m/d", $val['tsDay']);
//$strDate = explode('/', $strDate);
$jsResult[$val['tsDay']] = '['.($val['tsDay']*1000).', '.$val['nPrice'].']';
}
$jsResult = "[\n".implode(",\n", $jsResult)."\n]";
?>
the chart:
$(document).ready(function() {
var data = <?php echo $jsResult; ?>;
// create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'graph',
zoomType: 'x'
},
navigator : {
series : {
data : data
}
},
rangeSelector : {
selected : 5 // All
},
tooltip: {
xDateFormat: '%Y-%m-%d %H:%M:%S'
},
xAxis : {
ordinal: true
},
series : [{
//type: 'candlestick',
name : 'data',
data : data,
dataGrouping : {
enabled : false
},
marker: {
enabled: true,
radius: 2
}
}]
});
Sample data from Highcharts that draws fine:
[1121212800000,38.35],
[1121299200000,40.75],
[1121385600000,41.55],
[1121644800000,41.49],
[1121731200000,43.19],
[1121817600000,43.63],
[1121904000000,43.29],
[1121990400000,44.00],
[1122249600000,43.81],
[1122336000000,43.63],
[1122422400000,43.99],
[1122508800000,43.80],
[1122595200000,42.65],
A sample of my data:
[1339736400000,1627.25],
[1339650000000,1613.50],
[1339563600000,1619.50],
[1339477200000,1603.50],
[1339390800000,1584.00],
[1339131600000,1576.50],
[1339045200000,1606.00],
[1338958800000,1635.00],
[1338526800000,1606.00],
[1338440400000,1558.00],
[1338354000000,1540.00],
[1338267600000,1579.50],
[1337922000000,1569.50],
here is what's wrong with your chart your array going backwords with time you start with jun 15 then 14 ,13 and so on
if you use reverse() you will get an array looks like this
var data = [ [1337922000000,1569.50], [1338267600000,1579.50] ,
[1338354000000,1540.00],[1338440400000,1558.00],
[1338526800000,1606.00],
[1338958800000,1635.00],[1339045200000,1606.00],
[1339131600000,1576.50],[1339390800000,1584.00],
[1339477200000,1603.50],[1339563600000,1619.50],]
this will make your chart works fine here is a working jsFiddle

Resources