Highcharts Date.UTC does not work properly for real data - javascript

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

Related

How to display single data-values with ApexCharts correctly?

I am currently trying to build a barchart with ApexCharts. Everything works fine when the data-array has more than one entry. Somehow, whenever data only contains one element, the diagram messes up the width of the bar.
Correct state with multiple entries:
Buggy state with one entry
My goal is to display a single value with the same xaxis scale and the same barwitdh as the barchart displays multiple values.
I already tried using an array of timestamps for each hour as catigories-prop but this didn't work for me.
I use 'dateime' as type for my xaxis.
Data is an array that can contain 0, 1 or x entries. It is given to the Barchart-Component as data-prop.
Categories contains a the timestamp to each entry of data. Therefore it can also have 0, 1, or x values. Categories is used as the Barcharts categories-prop.
Here are my configurations (For the buggy state):
var options = {
series: [
{
name: "Servings",
data: [[1669082400000, 44]]
}
],
chart: {
height: 350,
type: "bar",
animations: {
enabled: false
},
zoom: {
enabled: false
}
},
dataLabels: {
enabled: false
},
xaxis: {
type: 'datetime',
labels: {
datetimeUTC: false,
datetimeFormatter: {
year: 'yyyy',
month: 'MMM',
day: 'dd',
hour: 'HH:mm'
}
},
categories: [
1669082400000,
],
min: 1669075200000,
max: 1669161600000
},
tooltip: {
intersect: false,
shared: true
},
yaxis: {
reversed: false,
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
Would be nice if somebody could help me out, I'm tripping over this one.

Dynamic update multible series Highcharts with single point XML file

I am a bit out of my comfort zone, since I normally do analytics and not fancy front-ends. However, I would like to have a real-time demo of some of my work, so it becomes easier to understand and not just numbers in a matrix. I have looked around and found something semi-relevant and come this far:
(It has four series like I want to and it iterates - to some degree)
https://jsfiddle.net/023sre9r/
var series1 = this.series[0],
series2 = this.series[1],
series3 = this.series[2],
series4 = this.series[3];
But I am totally lost on how to remove the random number generators without loosing nice things like the number of data points in a view (seems to depend on the for loop?!). Remove the extra title "Values" right next to my real y-axis title. And of cause how to get a new data point from a XML-file every second.
Ideally I want to have an XML-file containing 4 values, which I update approximately every 200ms in MATLAB. And every second I would like my 4 series chart to update. Is it not relatively easy, if you know what you are doing?! :-)
Thanks in advance!
I simplified your example and added clear code showing how to fetch data from server and append it to your chart using series.addPoint method. Also if you want to use XML, just convert it to JS object / JSON.
const randomData = () => [...Array(12)]
.map((u, i) => [new Date().getTime() + i * 1000, Math.random()])
Highcharts.chart('container', {
chart: {
renderTo: 'container',
type: 'spline',
backgroundColor: null,
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load () {
const chart = this
setInterval(() => {
// Fetch example below (working example: https://github.com/stpoa/live-btc-chart/blob/master/app.js)
// window.fetch('https://api.cryptonator.com/api/ticker/btc-usd').then((response) => {
// return response.json()
// }).then((data) => {
// chart.series[0].addPoint({ x: data.timestamp * 1000, y: Number(data.ticker.price) })
// })
chart.series.forEach((series) => series.addPoint([new Date().getTime(), Math.random()], true, true))
}, 3000)
}
}
},
title: {
text: null
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: [{
title: {
text: 'Temperature [°C]',
margin: 30
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
}, {
}],
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' + Highcharts.numberFormat(this.y, 4);
}
},
legend: {
enabled: true
},
exporting: {
enabled: false
},
rangeSelector: {
enabled: false
},
navigator: {
enabled: false
},
scrollbar: {
enabled: false
},
series: [{
name: 'Setpoint',
data: randomData()
}, {
name: 'Return',
data: randomData()
}, {
name: 'Supply',
data: randomData()
}, {
name: 'Output',
data: randomData()
}]
})
Live example: https://jsfiddle.net/9gw4ttnt/
Working one with external data source: https://jsfiddle.net/111u7nxs/

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

Formatting dates in HighCharts

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.

High Chart - columnrange Type depending on months

Hi every one I am using Highchart of columnrange type, i got chart from
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/columnrange/ and modified it according to my need , now i need months name in the x-axis and y-axis values are fixed . Currently i am not able to change the x-axis numbers to months.
My script is as :
$(function () {
$('#container').highcharts({
chart: {
type: 'columnrange',
inverted: true
},
title: {
text: 'Employee Bill Pending Detail'
},
subtitle: {
text: 'Month Wise'
},
xAxis: {
categories: ['Bank Bill Pending', 'Clam Pending']
},
yAxis: {
title: {
text: 'Session (2013-14)'
}
},
tooltip: {
valueSuffix: ''
},
plotOptions: {
columnrange: {
dataLabels: {
enabled: true,
formatter: function () {
return this.y ;
}
}
}
},
legend: {
enabled: false
},
series: [{
name: 'Months',
data: [
[1, 4], // Here the [1,4] denotes months between 'Jan' & 'Apr'.
[2, 8] // Here the [2,8] denotes months between 'Feb' & 'Aug'.
]
}]
});
});
Any help will be highly appreciable.
This is actually really easy. Relevant API documenation:
dateFormat()
yAxis.type
You need to set your data up like this (or use explicit js timestamp):
series: [{
name: 'Months',
data: [
[Date.UTC(2013, 0, 1), Date.UTC(2013, 3, 1)], // Here the [1,4] denotes months between 'Jan' & 'Apr'.
[Date.UTC(2013, 2, 1), Date.UTC(2013, 7, 1)] // Here the [2,8] denotes months between 'Feb' & 'Aug'.
]
}]
Note that Data.UTC() is zero based so that January is '0'. The last element in that list is the date. Since your data is just by month I made it '1'. You can have whatever you want here as the display on the dataLabel and the tooltip is handled with the dateFormat.
Example jsFiddle.

Categories