Issue parsing JSON for use as data in HighCharts - javascript

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

Related

Technique to use to reduce the number of javascript lines to write

i am making a web page where i am having many graphs like the ones here
http://vz.comxa.com/v2/
I am using highcharts JavaScript charting library. To make one chart you write the code like shown here http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-time-series/
$(function () {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=usdeur.json&callback=?', function (data) {
$('#container').highcharts({
chart: {
zoomType: 'x'
},
title: {
text: 'USD to EUR exchange rate over time'
},
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: 'Exchange rate'
}
},
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
}]
});
});
});
and the html
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
Since my charts are placed in modals,does it mean i must have the javascript for each chart in the page header. Due to the sheer number of charts involved,i reckon that's be a lot of JavaScript. What technique can i use to reduce the lines of javascript i will write?.
When building multiple charts you can reuse same options. One way could be to use Highcharts.merge function to add new options to the common ones.
Demo with Highcharts.merge in use - 2 charts: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/gauge-solid/
More complex option could be to create a custom series type with changed default options and optionally more features if required.
Demo - Sprakline: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/sparkline/

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

Highcharts not displaying data on live site

I'm writing a stacked bar chart that is working fine on my local machine, however when it is running on a live server it doesn't plot any of the data points. I've considered that it could be the api is taking longer on the live site to get the data, or maybe highcharts is not loading fast enough, but the x-axis populates the values correctly and the library is loading locally (also happens with CDN).
I can even log the values of the chart series and see everything fine. It just doesn't display any data with a line designating 0 on the Y axis. Anyone have any idea what the issue could be?
$.getJSON( 'URL TO API', function(data){
// Sample data output
// data = [
// { 'name' : 'Items', data : [ 'item1', 'item2', 'item3'] }
// { 'name' : 'losses', data : [2, 3, 1] }
// { 'name' : 'Wins', data : [5, 2, 0] }
// ]
var chart = new Highcharts.Chart({
chart: {
type: 'bar',
renderTo: 'chart',
},
title: {
text: 'Wins and Losses'
},
xAxis: {
categories: data[0]['data']
},
yAxis: {
min: 0,
allowDecimals: false,
title: {
text: 'Total'
}
},
legend: {
reversed: true
},
plotOptions: {
series: {
stacking: 'normal',
}
},
series: [
{
name : data[1]['name'],
data : data[1]['data']
},
{
name : data[2]['name'],
data : data[2]['data']
},
]
});
});

Unable to correctly position the tooltip content in HighCharts

I am using HighCharts combination chart to compare a forecast value(indicated by line) and a cumulative value (indicated by column). The cumulative value keeps increasing weekly and I want to be able to see if it reaches the predicted forecast value.
I created a graph in this js fiddle, http://jsfiddle.net/aroauy4t/ .
I have shown the js code below.
$(function () {
$('#container').highcharts({
title: {
text: 'Forecast Vs Cumulative chart'
},
xAxis: {
categories: [' ', ' ', 'Bananas', ' ', ' ']
},
labels: {
items: [{
style: {
left: '50px',
top: '18px',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'black'
}
}]
},
series: [{
type: 'column',
name: 'Cumulative',
data: [0, 0, 5, 0, 0]
}, {
type: 'line',
name: 'Forecast',
data: [3, 3, 3, 3, 3],
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
}
}]
});
});
But the tooltip content overflows when the x axis doesn't contain a label like in the image shown below.
How can I get the tooltip to behave without any overflow (like in the image below)
You could also make use of tooltip - useHTML property.
When turned on the tooltip is rendered as excepted.
tooltip: {
useHTML: true
}
http://jsfiddle.net/aroauy4t/2/
I got it to work (I don't know HighCharts very well) by using the following in your js fiddle:
categories: ["\u00A0", "\u00A0", 'Bananas', "\u00A0", "\u00A0"]
00A0 is the unicode character for non-breaking space.
Maybe it will work for you.

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

Categories

Resources