Working with JSONP Object in Highcharts - javascript

I have working JSONP being passed from my server. The JSONP (with the $.getJSON padding) looks like this:
jQuery21009647691948339343_1398527630522([
{
"name": 'World Federation of Democratic Youth',
"data": [16]
},
{
"name": 'Poqilet',
"data": [13]
},
{
"name": 'United Society',
"data": [8]
},
{
"name": 'Japvia',
"data": [589]
},
{
"name": 'the Mars',
"data": [1]
},
{
"name": 'The Americas',
"data": [913]
},
{
"name": 'High Orion Alliance',
"data": [1]
}
])
The PHP script I am using to pass this to my client is this:
header("content-type: application/json");
$array = (file_get_contents('data.json'));
echo $_GET['callback']. '('. ($array) . ')';
Now, when I get this object I want to put it into a Highcharts series
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Update Order'
},
xAxis: {
categories: ['Regions']
},
yAxis: {
min: 0,
title: {
text: 'Number of Nations'
}
},
legend: {
backgroundColor: '#FFFFFF',
reversed: true
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{}]
};
var url = "http://myserver.org/requestjsonp.php?callback=?";
$.getJSON(url, function (data) {
console.log(data);
options.series.data = data;
var chart = new Highcharts.Chart(options);
});
});
This is not working and I do not understand why, as I have worked through the errors I was getting before. Now I get no errors in the console, I just get nothing.
If I paste the contents of the JSON into the series, I get what I want, although I have to take out the first "{" and the last "}" character. Is this the problem? How can I remove them from an object if they are required to be in the JSON so that it can get passed to the client?
.remove() and other jquery methods I tried to trim the data once I received it didn't work.
console.log(data) now provides an array of 7 objects, which I believe is in line with data.json (seven name/data pairs).
Thank you for your consideration! :)

Your JSONP is incorrect. Without the padding it would look like:
{
name: 'World Federation of Democratic Youth',
data: [16]
},
{
name: 'Poqilet',
data: [13]
},
This is not valid JSON. It should probably look like:
[{
"name": "World Federation of Democratic Youth",
"data": [16]
},
{
"name": "Poqilet",
"data": [13]
}]
You probably also just want to do options.series = data since data will be an array.

In your JSON you have structre of series, not points. Because you use data[] paramter inside. In other words it should be:
options.series = data;

It turns out the JSONP data was not formatted correctly for Highcharts, so what I did was made it look like this (with padding):
jQuery21009184384981635958_1398737380163([{"name": "Regions","data": ["World Federation of Democratic Youth", "Poqilet", "United Society", "Japvia", "the Mars", "The Americas", "High Orion Alliance"]},{"name": "Number of Nations","data": [16, 13, 5, 566, 1, 926, 1]}])
And the Javascript to utilize it:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Update Order',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Number of Nations'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON('http://myserver.org/requestjsonp.php?callback=?', function(data) {
options.xAxis.categories = data[0]['data'];
options.series[0] = data[1];
chart = new Highcharts.Chart(options);
});
});
This works for the small JSONP excerpt that I posted, but not for my full set of data, which contains over 10,000 values and was throwing up a Highcharts Error 19 (http://www.highcharts.com/errors/19) message, so I will be trying to do a master-detail chart to deal with the large amount of data, but this should work for you if you have a small dataset.
For more on how highcharts data should be formatted, you can go here: http://www.highcharts.com/docs/chart-concepts/series/#1

Related

Highcharts data csv load

i'm having trouble displaying chart from my csv file.it doesn't plot chart. maybe my parser it is the problem. firebug says no major errors but i'm stuck i dont know how to make it work. please help..
this is how my csv looks like:
1437931522,30
1437931555,30.25
1437931768,30.25
1437931785,29.75
1437931802,30.25
1437932702,30.5
1437933601,29.75
1437933974,30
end of file is \n, but seems to not showing right here so I inserted extra enter
this is the code:
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: true
}
});
var mydata = [];
var times = [];
$.get('data.csv', function(data) {
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if(lineNo=>0)
{
times.push(new Date(items[0]*1000).toUTCString());
mydata.push(items[1])
}
});
});
$('#container').highcharts({
title: {
text: 'Temperature',
x: -20 //center
},
subtitle: {
text: 'test1',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%b %e, %Y',
year: '%Y'
},
categories: times
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Temp',
data: mydata
}]
});
});``
is it ok, to get csv just with 'data.csv' if it is in the same directory or I have to set entire url?
this ismy fiddle:
http://jsfiddle.net/skoky2/yw25z6ow/1/
You should use the following code in your main module
data: {
csv: csv
},
Ref: data-module
1) If you use datetime type of xAxis, you should no use categories. You can define tickPositions
2) Point value should be number not string, so replace:
mydata.push(items[1])
with
mydata.push(parseFloat(items[1]))
i managed to get it work. but I noticed that this chart works only in IE 8, not in firefox or chrome. firefox with ie tab aslo works

Using JSON file in Highcharts

I have a series of high and low temperatures that I would like to display in a column range chart with Highcharts.
I would specifically like a chart like the one shown in the demo example at: http://www.highcharts.com/stock/demo/columnrange
I have placed my data in a file called datatest.json, and it contains this text:
[
[1230771600000, -5.8, 10.1],
[1230858000000, -4.1, 1.4],
[1230944400000, -0.5, 4.1],
[1231030800000, -8.9, -0.7],
[1231117200000, -9.7, -3.7],
[1231203600000, -3.4, 3.2],
[1231290000000, -3.9, -0.2],
[1231376400000, -2.4, 6.7],
[1231462800000, 3.8, 6.9],
[1262221200000, -12.2, -6.5]
]
When I load the data from the file, it doesn't give me a chart. For example, with this:
$(function () {
$.getJSON('data/datatest.json', function (data) {
$('#container').highcharts('StockChart', {
chart: {
type: 'columnrange'
},
rangeSelector: {
selected: 2
},
title: {
text: 'Temperature variation by day'
},
tooltip: {
valueSuffix: '°C'
},
series: [{
name: 'Temperatures',
data: data
}]
});
});
});
But if I put the data directly into my code (as follows), it does display the chart as I expect:
$(function () {
$('#container').highcharts('StockChart', {
chart: {
type: 'columnrange'
},
rangeSelector: {
selected: 2
},
title: {
text: 'Temperature variation by day'
},
tooltip: {
valueSuffix: '°C'
},
series: [{
name: 'Temperatures',
data: [
[1230771600000, -5.8, 10.1],
[1230858000000, -4.1, 1.4],
[1230944400000, -0.5, 4.1],
[1231030800000, -8.9, -0.7],
[1231117200000, -9.7, -3.7],
[1231203600000, -3.4, 3.2],
[1231290000000, -3.9, -0.2],
[1231376400000, -2.4, 6.7],
[1231462800000, 3.8, 6.9],
[1262221200000, -12.2, -6.5]
]
}]
});
});
I think that I am either formatting the data incorrectly in my data file, or that I'm not reading from the file in the proper way.
Any suggestions or guidance to help me get on the right track would be much appreciated.
Credit to #SebastianBochan for directing my attention to the fact that my JSON was not valid.
Here is an abbreviated clip of what the correctly formatted JSON looks like:
{
"data":
[
[1420640460000,36.7,37.25],
[1420640520000,37.19,37.74],
[1420640580000,37.74,38.6],
[1420640640000,38.72,39.33],
[1420640700000,39.33,39.51]
]
}
I used a JSON validator: http://jsonformatter.curiousconcept.com/
It didn't matter whether I called it "data" or "temperature" It just had to be a string, and then when I referenced it, I needed to be sure to reference it as data.data. If I had called it "temperature" then it would have been data.temperature. In any case, here is the bit of code:
series: [{
data: data.data
}]

How do I make a Tornado Chart using Highcharts

I am trying to prepare a Tornado Chart using the column chart in Highcharts. Here is my fiddle.
My current code is:
$('#container').highcharts({
chart: {
type: 'columnrange',
inverted: true
},
title: {
text: 'Net Sales'
},
subtitle: {
text: 'MM $'
},
xAxis: {
categories: ['Annual Revenue', 'Number of Years', 'Annual Costs']
},
yAxis: {
title: {
text: 'MM $'
}
},
plotOptions: {
columnrange: {
dataLabels: {
enabled: true,
formatter: function () {
return this.y;
}
}
},
scatter:{
marker:{
symbol:'line',
lineWidth:11,
radius:8,
lineColor:'#f00'
}
}
},
legend: {
enabled: false
},
series: [{
name: 'Temperatures',
data: [
[12.15, 46.86],
[15.45, 42.28],
[27.77, 31.24]
]
},
{
name:'Base',type: 'scatter',data:[120],
}]
});
The problem is that the last series (Annual Costs) does not show, as it is in reversed order. Also, I'd like the Tornado Chart to look more like this:
Note that the labels in this chart are different from the actual values plotted. Also note that the bar in the center - in the example code, there would be a vertical line at 29.5. I would also like to support a combined uncertainty bar like the one at the bottom. Any suggestions would be greatly appreciated.
Your last bat is not showing, because first number is lower than second, see: http://jsfiddle.net/kErPt/1/
If you want to display another values at labels, then add that info first. Example:
data: [{
low: 12,
high: 15,
lowLabel: 35,
highLabel: 46
}, {
low: 2,
high: 35,
lowLabel: 15,
highLabel: 26
} ... ]
And then use dataLabels.formatter for series.
To add vertical line use plotLines.
I'm not sure what is the last bar called 'combined uncertainty'.
I've used Highcharts with separate series (thanks jlbriggs) to create a Tornado Chart: http://jsfiddle.net/uRjBp/
var baseValue = 29.5;
var outputTitle = "Net Sales";
var chart = new Highcharts.Chart({
chart: {
renderTo:'container',
//type:'column'
//type:'area'
//type:'scatter'
//type:'bubble'
},
credits: {},
exporting: {},
legend: {},
title: {
text: outputTitle
},
subtitle: {
text: "MM $"
},
tooltip: {
formatter: function() {
var msg = "";
var index = this.series.chart.xAxis[0].categories.indexOf(this.x);
var low = round(this.series.chart.series[0].data[index].y+baseValue);
var high = round(this.series.chart.series[1].data[index].y+baseValue);
if (this.x === "Combined Uncertainty") {
msg = "Combined Uncertainty in "+outputTitle+": "+low+" to "+high;
} else {
var lowLabel = this.series.chart.series[0].data[index].label;
var highLabel = this.series.chart.series[1].data[index].label;
msg = '<b>'+outputTitle+'</b> goes from '+ low +' to '+ high+'<br/> when '+this.x +
' goes from <br/> '+lowLabel+" to "+highLabel;
}
return msg;
}
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
formatter: function () {
var index = this.series.chart.xAxis[0].categories.indexOf(this.x);
if (this.series.userOptions.labels === undefined) {
return this.y+baseValue;
}
return this.key === "Combined Uncertainty" ? "":this.series.userOptions.labels[index];
}
}
}
},
xAxis: {
title: {
text: 'Factor'
},
allowDecimals:false,
categories: ['Annual Revenue', 'Number of Years', 'Annual Costs', 'Combined Uncertainty']
},
yAxis: {
title: {
text: 'MM $'
},
labels: {
formatter:function() {
return this.value+baseValue;
}
}
},
series:[{
name: 'Low',
grouping:false,
type:'bar',
data:[{y:12.15-baseValue, label:10},{y:15.45-baseValue, label:1},{y:31.25-baseValue, label:2},{y:12.15-baseValue, color:'#99CCFF', label: ""}],
labels:[10,1,2,]
},{
name: 'High',
grouping:false,
type:'bar',
data:[{y:46.86-baseValue, label:30},{y:42.28-baseValue, label:3},{y:27.77-baseValue, label:4},{y:46.86-baseValue, color:'#99CCFF', label:""}],
labels:[30,3,4,]
},
{
name: 'Median',
type: 'scatter',
data: [null,null, null,27-baseValue],
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
}
}]
});
function round(num) {
return Math.round(num*100)/100;
}
usually, this kind of chart is done using a separate series for the left and right portions
One way to do this is by setting one set of data as negative numbers, and then using the formatters to make the axis labels, datalabels, and tooltips display the absolute values
example:
http://jsfiddle.net/jlbriggs/yPLVP/68/
UPDATE:
to show a line as in your original chart, you can extend the marker symbols to include a line type, and use a scatter series to draw that point:
http://jsfiddle.net/jlbriggs/yPLVP/69/
If you don't want to have the extra code for the line marker type, you could use any of the other existing marker symbols for the scatter series.

Displaying array values in Bar chart of HighCharts

I am trying to display values which I am getting dynamically. In the below code I am trying to store the values in array and I am trying to use the array values in "series: data".
Nothing is getting displayed in the graph.
I know this is very simple question but I did not get any satisfactory answer when I googled it. Please help
var x = window.location.search.replace( "?", "" );
x = x.substring(3);
var array = x.split(","); // I am storing my dynamic values in this array
$(function () {
//alert(array); ----- I am able to see the values here
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Wireless Experience Meter'
},
subtitle: {
text: 'Sub - Time to Download'
},
xAxis: {
categories: ['Text'],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Time (ms)',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ' ms'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -40,
y: 100,
floating: true,
borderWidth: 1,
backgroundColor: '#FFFFFF',
shadow: true
},
credits: {
enabled: false
},
series: [{
name: 'Attempt 1',
//data: [635, 203, 200]
data : [array[0]] // I need to pass the variables here to get it displayed
}, {
name: 'Attempt 2',
//data: [133, 408, 698]
data : [array[1]]
}, {
name: 'Attempt 3',
//data: [973, 914, 4054]
data : [array[2]]
}]
});
});
You don't tell us what the variable array equals but since its generated from x.split(","), it's elements are going to be strings and not the numeric values Highcharts needs.
So convert it with parseInt or parseFloat:
var numericData = [];
for (var i = 0; i < array.length; i++){
numericData.push(parseFloat(array[i]));
}
...
series: [{
name: 'Attempt 1',
data : numericData
},
...
[array[0]] is not an array, that looks like console output not javascript. But [[0]] or [0] technically would be. However, since a call to array (array(0)) generates an array then I think you want data: array(0).
Outside shot at data : [array(0)] if you didn't show the example data correctly. I've never used HighCharts so I don't know what it's expected but I still go with data : array(0)

HighCharts: Logarithmic Scale for Horizontal Bar Charts

I am working with HighCharts to produce a bar chart. My values can range from as minimal as 0 to as high as 100k (example). Therefore, one bar of the graph can be very small and the other can be very long. HighCharts has introduced the feature of "Logarithmic Scaling". The example of which can be seen HERE
My js code is written in this jsfiddle file. I want to display my horizontal axis (x-Axis) logarithmically. I have inserted the key type as shown in the example but the script goes into an infinite loop which has to be stopped.
What is the flaw in the execution or is logarithmic scaling for HighCharts still not mature?
P.S The commented line in jsfiddle is causing the issue
Since the "official" method is still buggy, you can achieve the log scale more manually by manipulating your input data with a base 10 log and masking your output data raising 10 to the output value. See it in action here http://jsfiddle.net/7J6sc/ code below.
function log10(n) {
return Math.log(n)/Math.log(10);
}
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'bar',
marginRight: 200,
marginLeft: 10,
},
title: {
text: 'Negative'
},
xAxis: {
categories: [''],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: '',
align: 'high',
},
labels: {
formatter: function() {
return Math.round(Math.pow(10,this.value));
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -50,
y: 100,
floating: true,
borderWidth: 1,
shadow: true
},
tooltip: {
formatter: function() {
return '' + this.series.name + ': ' + Math.round(Math.pow(10,this.y)) + ' millions';
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
formatter: function() {
return Math.round(Math.pow(10,this.y));
}
}
}
},
credits: {
enabled: false
},
series: [{
"data": [log10(4396)],
"name": "A"},
{
"data": [log10(4940)],
"name": "B"},
{
"data": [log10(4440)],
"name": "C"},
{
"data": [log10(2700)],
"name": "D"},
{
"data": [log10(2400)],
"name": "E"},
{
"data": [log10(6000)],
"name": "F"},
{
"data": [log10(3000)],
"name": "G"},
{
"data": [log10(15000)],
"name": "E"}],
});
It is still experimental according to the Official Documentation, so that might be the case:
"The type of axis. Can be one of "linear" or "datetime". In a datetime axis, the numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days.
As of 2.1.6, "logarithmic" is added as an experimental feature, but it is not yet fully implemented. Defaults to "linear".
Try it: "linear", "datetime" with regular intervals, "datetime" with irregular intervals, experimental "logarithmic" axis."
For those of you who are still looking for an answer :
JSFiddle : http://jsfiddle.net/TuKWT/76/
Or SO snippet :
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'bar'
},
title: {
text: 'Negative'
},
xAxis: {
categories: ['A','B','C','D','E','F','G','H'],
title: {
text: null
}
},
yAxis: {
type: 'logarithmic',
//min: 0, <= THIS WILL CAUSE ISSUE
title: {
text: null,
}
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
return this.x + ':' + this.y + ' millions';
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: false
}
}
},
credits: {
enabled: false
},
series: [{
"data": [4396,4940,4440,2700,2400,6000,3000,15000],
}],
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 300px"></div>

Categories

Resources