Formatting dates in HighCharts - javascript

I have the following code:
<script>
$.getJSON('https://www.quandl.com/api/v3/datasets/OPEC/ORB.json?order=asc', function(json) {
var hiJson = json.dataset.data.map(function(d) {
return [new Date(d[0]), d[1]]
});
// Create the chart
$('#container').highcharts('chart', {
rangeSelector: {
selected: 1
},
title: {
text: 'OPEC Crude Oil Price',
},
series: [{
type: 'line',
name: 'OPEC',
data: hiJson,
}]
});
});
Which prints a beautiful chart as follows:
OPEC Crude Oil Price
But as you can see, the dates are not in the correct format. I am struggling to work out what is wrong?
All help much appreciated as always!
UPDATE:
So thanks to Holvar's comment I solved one problem, but now I have another on the same theme.
My code is as follows:
<script>
$.getJSON('https://www.quandl.com/api/v3/datasets/BOE/IUAAAMIH.json?auth_token=pg6FBmvfQazVFdUgpqHz&start_date=2003-01-02&order=asc', function(json) {
var hiJson = json.dataset.data.map(function(d) {
return [new Date(d[0]), d[1]]
});
// Create the chart
$('#interest').highcharts('chart', {
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%Y'
}
},
rangeSelector: {
selected: 1
},
title: {
text: 'UK Interest Rates',
},
series: [{
type: 'line',
name: 'Interest Rate',
data: hiJson,
}]
});
});
But this produces a chart without dates on the bottom. I'd like years from 2003-01-02. The chart looks like this
UK Interest Rate
I don't understand why it's not showing an annual date as in the solution to the initially posed question?!
You help is much appreciated!

I believe the issue is with the way the data map is happening. The ending array contains multiple arrays, instead of an object with "x" and "y" properties. Try changing the initialization of the hiJson variable to something like:
var hiJson = json.dataset.data.map(function(d) { return { x: new Date(d[0]), y: d[1] }; });
That seems to be working on my local environment.

Related

Reduce the number of lines

I have defined two charts below for example. But I use more than 50 charts in my code.
The difference between both charts are: chartNumber, containerNumber, id, text and data. Also the condition that is used for checking each chart at the beginning.
Working fiddle of the same: https://jsfiddle.net/2s93zb4j/12/ (pls check all 3 charts to view all of them)
Instead of repeating same lines of code for each chart, will I be able to reduce the number of lines using for loop or forEach. Thank you.
//Chart1
if (checkNA=== "NA")
chart0 = Highcharts.chart('container1', {
id: 1,
yAxis: [{
title: {
text: 'NorthAmerica'
}
}],
series: [{
data: NorthAmericaData,
type: 'line',
}],
});
}
//Chart2
if (checkSA=== "SA")
chart1 = Highcharts.chart('container2', {
id: 2,
yAxis: [{
title: {
text: 'SouthAmerica'
}
}],
series: [{
data: SouthAmericaDta,
type: 'line',
}],
});
}
A class would go a long way here.
class ChartObject {
constructor(id, text, data) {
this.id = id;
this.yAxis = [
{
title: {
text,
},
},
];
this.series = [
{
data,
type: 'line',
},
];
}
}
//Chart1
if (checkNA === 'NA') {
chart0 = Highcharts.chart(
'container1',
new ChartObject(1, 'NorthAmerica', NorthAmericaData)
);
}
//Chart2
if (checkSA === 'SA') {
chart1 = Highcharts.chart(
'container2',
new ChartObject(2, 'SouthAmerica', SouthAmericaDta)
);
}
Hope this helps.

Highcharts Date.UTC does not work properly for real data

I've built something like this. I get my data from the server, put it in an object called series, and pass it to 'series' in Highcharts code block. Basically, for every staff, there will be a date, and my default value(Y-Axis) is '1' for now. However, I can't get dates on the chart as expected even if it looks that I had correct data and did correct parsing. Unexpectedly, I get my millisecond values as Y-axis values, which does not make any sense, and every staff has a default date, which is 1 January. (For ex., staff 1, 1 January, x-axis value = 1554422400000)
I get dates like this, 19-02-2019 17:32. Then I split them, and use it like this,
([Date.UTC(parseInt(yearsplit[0]), datesplit[1]-1, parseInt(datesplit[0])), 1])
which looks exactly the same format in Highcharts, ([Date.UTC(1971, 2, 16), 0.86])
var responsePromise = $http.post('statistics/getAllProtocolRecords', data, null);
responsePromise.success(function (dataFromServer, status, headers, config) {
var series = [{
name: "",
data: []
}];
dataFromServer.protocolRecords.forEach((data) => {
var datesplit = data.checkupDate.split("-");
var yearsplit = datesplit[2].split(" ");
series.push({
name: data.staff,
data: [Date.UTC(parseInt(yearsplit[0]), datesplit[1]-1, parseInt(datesplit[0])), 1]
})
});
series.shift();
Highcharts.chart('container', {
chart: {
type: 'spline'
},
title: {
text: 'Toplam Muayene Kaydı (' + sysrefHcCheckupType + ')'
},
subtitle: {
text: ''
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
title: {
text: 'Tarih'
}
},
yAxis: {
title: {
text: 'Toplam Muayene (Gün)'
},
min: 0
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x:%e. %b}: {point.y:%f} '
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
colors: ['#00bdff', '#FF0700', '#df0300', '#ff0700', '#c0df00'],
series: series
});
});
I've just realized that I'd made a little mistake in push function. In series.push, 'data' should like this, surrounded by array brackets:
data: [
[ Date.UTC(parseInt(yearsplit[0]), parseInt(datesplit[1])-1, parseInt(datesplit[0])), 1]
]

Highcharts showing ticks number, instead of date

I'm trying to create a graph from JSON received from a web API.
I had it working, and then decided to start refactoring.
After a while I suddenly noticed that the xAxis no longer shows dates, but instead it seems to be showing ticks.
I'm quite inexperienced with JavaScript and even more so with highcharts so I cannot spot my mistake.
(source: mortentoudahl.dk)
The change I did was making an option object, and pass it to highcharts upon instantiation, according to the instructions found here:
http://www.highcharts.com/docs/getting-started/how-to-set-options
When I compare my code to the last code block in that link, it seems to be the same, except for the options object.
var pm10 = [];
var pm25 = [];
var options = {
chart: {
zoomType: 'x',
renderTo: 'container'
},
title: {
text: "Compounds in the air at HCAB"
},
subtitle: {
text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : "Pinch the chart to zoom in"
},
xAxix: {
type: 'datetime'
},
yAxis: {
title: {
text: 'µg/m³'
}
},
series: [{
name: 'Particles less than 2.5 µm',
data: pm25,
pointStart: Date.UTC(2016, 5, 8),
pointInterval: 86400 * 1000 // One day
}, {
name: 'Particles less than 10 µm',
data: pm10,
pointStart: Date.UTC(2016, 5, 8),
pointInterval: 86400 * 1000 // One day
}]
};
function ReverseAndSetArrays(data) {
$.each(data.reverse(), function(key, value) {
if ("PM10b" in value) {
pm10.push(value["PM10b"]);
};
if (!("PM10b" in value)) {
pm10.push(null);
};
if ("PM25b" in value) {
pm25.push(value["PM25b"]);
};
if (!("PM25b" in value)) {
pm25.push(null);
};
});
};
var url = "super secret url";
$.getJSON(url, function(data) {
ReverseAndSetArrays(data);
var chart = new Highcharts.Chart(options);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
The following configuration in your options object is incorrect:
xAxix: {
type: 'datetime'
}
It should be:
xAxis: {
type: 'datetime'
}

Highchart xAxis label steps wrong

I am loading Highcharts like this.
var options = {
credits: {
enabled: false
},
chart: {
renderTo: 'chart_box',
type: 'areaspline'
},
title: {
text: ''
},
xAxis: {
crosshairs: true,
labels: {
step: 5,
rotation: -45
}
},
series: []
};
Then I have a function which is called when graph needs to be loaded. Upon calling the function, data is fetched through AJAX and assigned to series and date lie this:
$.ajax({
url: 'url/charts',
type: 'post',
data: data
}).done(function(data) {
var dateCount = data.dates.length;
var stepCount = 1;
if (dateCount > 10) {
stepCount = 5;
}
options.xAxis.categories = data.dates;
$.each(data.series, function(name, elem) {
options.series.push({
name: name.replace('_', ' ').toUpperCase().trim(),
data: elem
})
});
chart = new Highcharts.Chart(options);
});
The issue here is that even though I have given step as 5 , it is showing dates with 15 dates interval. I mean in xAxis labels. It seems like it will be multiplied by three always. If I give 2, it will show 6 days interval in labels. Everything working fine in a chart which is not using AJAX to load data.

Highcharts JSON, chart not displaying

I have some data I wish to display on a chart but it just shows the title and no points get drawn. The JSON data I receive is correct as per my knowledge, I think it's somewhere in the chart function but I can't really point it out.
This is what I have so far:
data.php (the output):
{"name":"Temperature","data":[34,28,29,28,34,28,32,27,24,30,25,32,34,28,34,33,24,33,30,27,24,27,26,29]}
The important bits of the html:
<script>
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("data.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Temperature vs. Time',
x: -20 //center
},
xAxis: {
categories: ['12AM', '1AM', '2AM', '3AM', '4AM', '5AM', '6AM', '7AM', '8AM', '9AM', '10AM', '11AM','12PM', '1PM', '2PM', '3PM', '4PM', '5PM', '6PM', '7PM', '8PM', '9PM', '10PM', '11PM']
},
yAxis: {
title: {
text: 'Temperature'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
series: json
});
});
});
});
</script>
It's supposed to show temperature per hour but unfortunately nothing comes up. Any idea what could be wrong?
series should be an array. So you need to just change:
series: json
To:
series: [json]
Working example: http://codepen.io/anon/pen/Kfgsd
Documentation: http://www.highcharts.com/docs/chart-concepts/series
your problem i think that you haven't specified where your chart should be inserted to, afaik you either should specify the renderTo option for the class constructor options or use the $('#container').haighcharts({...}) jquery helper

Categories