Using JSON file in Highcharts - javascript

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
}]

Related

How to create Highcharts plotbands along every point in line chart

I want to create a linechart with HighCharts that has a plotband along every point of the line. Like so: https://imgur.com/a/WVj7uJb
(They are using HighCharts as well, so it must be possible).
However, I can't seem to manage getting it for every point specific. Whenever I add plotbands, it just draws a band using the highest and lowest point like so: https://imgur.com/a/PZdKIBz
How I currently render the chart (note the plotbands part):
Highcharts.chart('chart', {
chart: {
type: 'line',
},
title: {
text: `${this.variable}`,
},
credits: {
enabled: false,
},
xAxis: {
type: 'category',
title: {
text: "Date"
},
},
yAxis: {
title: {
text: this.unit
},
plotBands: [
{
color: "orange",
from: 12,
to: 14
},
{
color: "orange",
from: 10,
to: 13
} // and so on.
]
},
tooltip: {
headerFormat: `<div>Date: {point.key}</div>`,
pointFormat: `<div>${this.unit}: {point.y}</div>`,
useHTML: true,
},
series: seriesList,
} as any);
So exact example would render a plotband from 10 to 14 along the whole linechart, instead of to different points: one from 12 to 14, and one from 10 to 13.
Any ideas as to how I can accomplish this? I have seen something with 'path', but I can't find anything about it.
Thanks in advance.
In that case, you should use arearange series instead of plotBand.
Demo:
https://www.highcharts.com/demo/arearange-line
API Reference:
https://api.highcharts.com/highcharts/series.arearange

How to parse a string in HighMaps (Map Bubble) alongside country code?

I'm building a simple application where people from different countries select their country and occupation. I upload it to Firebase and then visualise it in HighMaps.
I'm using an example from here, but instead of the population number, I want my app to display different occupations of the people in that location.
This is the default data format:
joinBy: ['iso-a2', 'code'],
data: [{"code":"AL","z":500}],
I try to parse something like this:
joinBy: ['iso-a2', 'code'],
data: [{"code":"AL","occupation":"teacher"}],
the whole map breaks and displays nothing.
But is it possible to parse a string there or do Highmaps not allow it?
You have to update the series as
series: [{
name: 'Countries',
color: '#E0E0E0',
enableMouseTracking: false
}, {
type: 'mapbubble',
name: 'Population 2013',
joinBy: ['iso-a2', 'code'],
data: [{
"code": "AF",
"z": 30552,
"occupation":"teacher"
}, {
"code": "AL",
"z": 2897,
"occupation":"teacher"
}, {
"code": "DZ",
"z": 39208,
"occupation":"teacher"
}],
minSize: 4,
maxSize: '12%',
tooltip: {
pointFormat: '{point.code}: {point.z} thousands<br>Occupation:{point.occupation}'
}
}]
Here you have to update tooltip as
tooltip: {
pointFormat: '{point.code}: {point.z} thousands<br>Occupation:{point.occupation}'
}
where point.occupation represents occupation of data object { "code": "AF","z": 30552,"occupation":"teacher" },
Fiddle demo

Issue parsing JSON for use as data in HighCharts

I'm trying to create a chart using highcharts with dates on the x-axis.
I'm using the following example from the Highcharts website as it is almost exactly what I am trying to achieve.
Using getJson I am getting json from a URL in this format:
[[Date.UTC(2016,04,29),3],[Date.UTC(2016,04,30),1],[Date.UTC(2016,05,02),4]]
As you can see it is similar to the format used in the example. However I get the following error from getJson:
angular.js:12416 SyntaxError: Unexpected token D in JSON at position 2
I don't think Date.UTC is the issue, as when I remove it I still get an error for the next character "(".
When I remove the getJson function and simply hardcode the above values into data, exactly as it is formatted above, the chart renders perfectly. I don't understand how it works when I hardcode it but doesn't if not.
The code is as follows (exactly like in the official highcharts example really)
$(function () {
$.getJSON('http://localhost:8181/graphData', function (data) {
$('#container').highcharts({
chart: {
zoomType: 'x'
},
title: {
text: 'Visitors per day'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Num people'
}
},
legend: {
enabled: false
},
plotOptions: {
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
name: 'USD to EUR',
data: data
}]
});
});
});

Highcharts X-axis labels on the side

I'm using Highcharts, and I used to be able to get labels on the side. But it's not working now, am I missing something? The red arrow is where I would want the labels like in the following example.
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/bar-basic/
This is the code I'm using, I add the series in a dynamic way.
credits: {
enabled: false
},
chart: {
type: 'bar'
},
xAxis: {
categories: ['Jan', 'Feb'],
labels: {
enabled: true,
}
},
yAxis: {
min: 0,
max: 100,
title: {
text: 'Score',
align: 'high'
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
}
});
// Add Series
var detailchart = $('#chart-detail').highcharts();
var categories = new Array;
// Set Chart Title
detailchart.setTitle({text: results[0].category});
$.each(results, function(i, data){
categories.push(data.name);
detailchart.addSeries({
name: data.name,
data: [data.score]
});
});
detailchart.xAxis[0].setCategories(["1", "2"]);
$('#chart-detail').highcharts().reflow();
Results is an array that looks like this (I get it through ajax):
As I understand from your code here, you wish to specify two categories with names 1 and 2 but you are not specifying any data for second category, So the only category that is showing on your chart is 1. Your data array for each series must have elements per each category. For example if you have two category you should consider having two data elements in each series. In this line data: [data.score] you are just specifying one element in data array. Your code should be something like this: (make it dynamic per your need)
$.each(results, function(i, data){
categories.push(data.name);
detailchart.addSeries({
name: data.name,
data: [data.score, 40], //40 is some data for your second category.
});
});
Demo: http://jsfiddle.net/u6crkatv/
Only what you need is use 4 series, each of them with single data point.
series: [{
name: 'Year 1800',
data: [107]
}, {
name: 'Year 1900',
data: [138]
}, {
name: 'Year 2008',
data: [973]
},{
name: 'Year 20098',
data: [973]
}]
Example: http://jsfiddle.net/y9wzggc4/

Working with JSONP Object in Highcharts

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

Categories

Resources