Using hours value with HighCharts - javascript

I have some trouble with HighCharts, i can't figure out how to use hours. For now i manage to use day hours (00 to 24) but it stop at 24 and restart at 0 because HighCharts consider that a day is pass. I just want to have an hour value like 1h30 or 55h10 for example.
Here is my chart :
$('#chart2').highcharts({
chart: {
type: 'column',
plotBackgroundColor: null,
plotBorderWidth: 0,
borderWidth: 2,
borderRadius: 7,
borderColor: '#D8D8D8',
width:dialogWidth/2,
height:dialogWidth/2+50
},
title: {
text: 'Time Worked per Day'
},
xAxis: {
type: 'category'
},
yAxis: {
type: 'datetime', //y-axis will be in milliseconds
dateTimeLabelFormats: { //force all formats to be hour:minute:second
second: '%H:%M',
minute: '%H:%M',
hour: '%H:%M',
day: '%d %H:%M',
week: '%H:%M',
month: '%H:%M',
year: '%H:%M'
},
title: {
text: 'Hours'
}
},
credits: {
enabled: false
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
formatter: function() {
return Highcharts.dateFormat('%Hh%M',new Date(this.y));
}
}
}
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name +' : </b>' +
Highcharts.dateFormat('%Hh%M',new Date(this.y));
}
},
series: [{
name: 'Hours',
colorByPoint: true,
data: datas
}]
});
Hope you can help.

You don't need to use datetime for figuring this out. Since what you want to know is the number of hours per day, based on a value in milliseconds from your JSON data, you need to treat that value as a number, not a date.
Here's how I solved this problem:
First, I changed how you described the labels in your y-axis. I dropped the datetime type and used the formatter function to show the labels as whole hours. I also defined a tickInterval to show the labels one hour apart from one another.
yAxis: {
labels: {
formatter: function() {
// show the labels as whole hours (3600000 milliseconds = 1 hour)
return Highcharts.numberFormat(this.value/3600000,0);
}
},
title: {
text: 'Hours'
},
tickInterval: 3600000 // number of milliseconds in one hour
},
Next, I updated the code in your tooltip. We're taking your y values and making them whole hours. I set the second parameter in Highcharts.numberFormat to "2" so your toolip values show up with two decimal places (such as "2.50" for two-and-one-half hours).
tooltip: {
formatter: function() {
return '<b>' + this.series.name +' : </b>' +
Highcharts.numberFormat(this.y/3600000,2);
}
},
You can see a working fiddle, based off the sample data you provided, here: http://jsfiddle.net/brightmatrix/kk7odqez/
Here's a screenshot I took of the chart in this fiddle, showing how both the labels and tooltip now appear:
Thank you for the additional information you provided in your comments. That really helped me puzzle this out and get you what I hope is a useful solution.

Related

Highcharts - cannot force x axis to stop on a certain date

I am using highcharts/highstock and I send some data to the client.
I tried various sets of settings, but I cannot force x axis to stop on a certain date.
For example, I create a chart that has data from 20/3/2019 to 25/3/2019. The interval must always be 5 minutes.
The starting point is correct, it starts in 20/3/2019.
But the last point is always a day more. Its about 35 more points of 26/3/2019, instead of stopping at 25/3/2019.
*if this changes anything, the starting point should be 20/3/2019 00:00 , but it actually starts at 20/3/2019 03:00 in highcharts.
My data are
{
time:{
useUTC:false
},
boost: {
enabled: true,
allowForce:true,
usePreallocated:true,
useGPUTranslations: true
},
chart: {
type: "line",
zoomType: 'x'
},
title: {
text: item.title
},
xAxis: {
type: 'datetime',
tickInterval: 5 * 60 * 1000 , /*5 min */
max: pointStop,
labels: {
format:'{value:%H:%M:%S}'
},
dateTimeLabelFormats: {
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%b. %e',
week: '%b. %e',
month: '%b. %y',
year: '%Y'
}
},
yAxis: {
title: {
text: item.title
},
alignTicks:'left',
textAlign:'left',
align:'middle',
opposite:false
},
series: [
{
boostThreshold: 150,
name: item.title,
pointStart: pointStart,
pointInterval: 5 * 60 * 1000,
data: item.array,
dataGrouping:{
approximation: 'average',
enabled:true,
forced:true,
groupAll:true,
groupPixelWidth:20
}
}
]
}
What am I doing wrong?
Thanks
It sounds like an issue setting the tick count. The documentation states
If a tickAmount is set, the axis may be extended beyond the set max in order to reach the given number of ticks. The same may happen in a chart with multiple axes, determined by chart. alignTicks, where a tickAmount is applied internally.
You need to disable oridinal option, which is enabled by default in Highstock:
xAxis: {
ordinal: false,
...
}
Live demo: http://jsfiddle.net/BlackLabel/6rqcLhp0/
API Reference: https://api.highcharts.com/highstock/xAxis.ordinal

Grouping dynamic data in highcharts

I'm attempting to create a highchart populated by dynamic data that looks something similar to the following image:
Where the y-axis (technically just the x-axis with the inverted: true tag) is a list of people grouped by location. However, I'm having trouble displaying the data grouped by their locations with the locations being displayed also. The actual view isn't important, just that it neatly groups the data and displays the location.
All I've managed to do so far is simply sort the data and tag the location name to the end of the person, but that's not quite what I want:
I'm aware that this is a relatively easy thing to do with categories and data series, but the only examples of this i could find didn't involve dynamic data. Here is some of my code so far:
function loadChart() {
//calculate height based on number of users displayed, and width based on the panel body width
var chartHeight = users.length * 20 + 75;
var chartWidth = $('#InOutPanelViewId').width();
chart = Highcharts.chart('ChartViewId', {
chart: {
width: chartWidth,
height: chartHeight,
type: 'columnrange',
inverted: true,
spacingLeft: 0
},
title: {
text: null
},
xAxis: {
showEmpty: false,
title: null,
type: 'category',
labels: {
align: 'right',
format: '{value.User}',
style: {
color: 'black',
fontSize: '12pt'
}
}
},
yAxis: {
showEmpty: false,
title: '',
type: 'datetime',
dateTimeLabelFormats: {
second: '%I:%M %P',
minute: '%I:%M %P',
hour: '%I:%M %P',
day: '%I:%M %P',
week: '%I:%M %P',
month: '%I:%M %P',
year: '%I:%M %P'
},
min: startTime.valueOf(),
max: endTime.valueOf(),
plotLines: [{
color: 'grey',
value: time,
width: 1.5
}]
},
legend: {
enabled: false
},
credits: {
enabled: false
},
series: [
{ name: "Data", borderWidth: 0, data: chartData }
],
tooltip: {
formatter: function () {
return '<b>' + this.point.jobcode + '</b><br>' + this.point.timespan + '<br>';
}
}
});
}
Where chartData currently looks like this:
chartData[chartData.length] = { name: user, low: displayStart.valueOf(), high: displayEnd.valueOf(), timespan: timeSpan, jobcode: value.JobCodeName, color: colour };
And is populated with dynamic data it pulls from an endpoint. The endpoint does also send back the location, so I'm wondering how I can use this structure and the location i'm sending back to group the data and display it nicely.
Any help is appreciated, thanks!

Highcharts addPoint function show nothing

In the first case i apologize for the bad english i'm french :D
So I recently tried to show some timed data on HighchartsJs.
I try to receive the data using ajax and I made a function that add all the point that i want.
But when I try to load it i see the information on the cursor but no point is shown ! :/
Here is my success function on AJAX request :
success: function(resultat){
function addPoint(){
var chart = $('#graphResult').highcharts();
for(i in resultat){
chart.series[0].addPoint([Date.UTC(year, month, day, resultat[i]["time"].split(":")[0]), resultat[i]["value"]], true);
}
}
$('#graphResult').highcharts({
chart: {
type: 'spline',
events: {
load: addPoint
}
},
title: {
text: 'Température du jour'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
minute: '%H:%M',
hour: '%H:%M',
},
title: {
text: 'Heure'
}
},
yAxis: {
title: {
text: 'Température (°C)'
},
min: 0
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.y:.2f} °C'
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
series: [{
name: "Température du " + String(day) + "/" + String(month) + "/" + String(year),
}]
});
}
As you can see, I have the information but no point is displayed : http://puu.sh/kwfnV/ad6302810a.png
As you said in comments, the problem is in data returned from server.
This is your Json:
[{"time":"09:00:00","value":"25"},{"time":"10:00:00","value":"30"}]
The "value" is string, then you have to parse as Float:
chart.series[0].addPoint(
[Date.UTC(year, month, day,
resultat[i]["time"].split(":")[0]),
parseFloat(resultat[i]["value"])], true
);
Fiddle: http://jsfiddle.net/69k80L58/4/

Correctly plot time series in Highcharts/Highstock

I have large collection of data in the format [1421065200000, 1.72], where the first parameter is time in milliseconds and the second parameter is the value at that specific time. I have data array consisting of such data in large size. Now I want scrollable graph containing plot of such time and value data. Here is my javascript implementation to do so,
var dataArray; //This contains my data array i.e. ([[t1, v1],[t2, v2],...])
var minDate = dataArray[0][0];
var maxDate = dataArray[dataArray.length - 1][0];
var chartOption = {
chart: {
type: graphType,
renderTo: 'graph-container',
zoomType: 'x',
useUTC: false
},
title: {
text: 'Data from last 24 hours'
},
credits : {
enabled: false
},
xAxis: {
title: {
text: null
},
type: 'datetime',
dateTimeLabelFormats: {
second: '%Y-%m-%d<br/>%H:%M:%S',
minute: '%Y-%m-%d<br/>%H:%M',
hour: '%Y-%m-%d<br/>%H:%M',
day: '%Y<br/>%m-%d',
week: '%Y<br/>%m-%d',
month: '%Y-%m',
year: '%Y'
},
allowDecimals: false,
ordinal: false,
min: minDate,
max: maxDate
},
yAxis: {
title: {
text: null
}
},
plotOptions: {
series: {
pointStart: minDate,
pointInterval: 5 * 60 *1000
}
},
series: [{
name: parameterName,
data: dataArray
}],
exporting: {
enabled: false
}
};
parameterChart = new Highcharts.Chart(chartOption);
}
The chart shows incorrect data, the time value on x-axis doesn't match the value at y-axis. What is the most correct and efficient to show such time series. Should I use Highcharts or Highstock. Please guide me through this, with suggestion or maybe with solution.
What I did was, I used HighStock instead of HighCharts (since I needed scrollbar along x-axis for large collection of data). I was passing the date in my local time zone format, whereas the chart was using UTC. So, I disabled the use of UTC (alternative: I could have provided data in UTC and drawn the graph using the same, In my case I needed my local labels). I gave the minimum and maximum range to the x-axis through x-axis min and max configuration. Here is the sample of my code,
//dataArray contains the array of data [[x1, y1], [x2, y2], ...]
//x is Date, y is temperature value (say)
var minDate = dataArray[0][0];
var maxDate = dataArray[dataArray.length - 1][0];
//Disable use of UTC
Highcharts.setOptions({
global: {
useUTC: false
}
});
//Create graph options
var chartOption = {
chart: {
type: graphType, //line, bar, column, etc
renderTo: 'graph-container', //div where my graph will be drawn
zoomType: 'x' //Making x-axis zoomable/scrollable
},
title: {
text: 'Data from last 6 hours'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' :
'Pinch the chart to zoom in'
},
xAxis: {
title: {
text: null
},
type: 'datetime', //For time series, x-axis labels will be time
labels: {
//You can format the label according to your need
format: '{value:%H:%m}'
},
min: minDate,
max: maxDate,
minPadding: 0.05,
maxPadding: 0.05
},
yAxis: {
title: {
text: null
}
},
scrollbar: {
enabled: true
},
series: [{
name: "Temperature", //Name of the series
data: dataArray
}],
exporting: {
enabled: false
},
credits : {
enabled: false
}
};
//Finally create the graph
var myChart = new Highcharts.Chart(chartOption);

Highcharts show days of month dates in X axis (from JSON file). tickInterval: not work?

I have another issue with Highcharts graphs. A PHP file returns a JSON whith many elements, compounds of two fields (name: date,int:). I need Highcharts draw all dates of the month in the X axis. The elements on JSON chain are all the same month.
I try whith many sintaxis of tickInterval (put 1, or put 24 * 3600 * 1000,...), but not works!
Thank you in advance!!!
NOTE: I tried to copy the code in jsFiddle, but does not work ... neither use jsFiddle :( ... sorry!
JSFiddle
Thanks wergeld!!
JSFiddle
JSON chain returned from PHP file:
[{"name":"Sant Iscle 60","data":[[1398902400000,4],[1399939200000,1]]},{"name":"Sant Iscle 62","data":[[1399939200000,2]]},{"name":"Laboratorio Comp.","data":[[1400025600000,2]]}]
Javascript file:
chart = new Highcharts.Chart({
chart: {
renderTo: 'divStatsGrupo',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'column'
},
title: {
text: tituloMes
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%d/%m/%Y',new Date(this.x)) + '<br/>' +'Alarmas: ' + this.y
}
},
xAxis: {
type: 'datetime',
tickInterval: 1, //<------NOT WORKING?¿
labels: {
style: {
fontSize: '13px',
fontFamily: 'Arial,sans-serif'
}
},
dateTimeLabelFormats: { // don't display the dummy year
day: '%e. %b',
}
},
yAxis: {
tickInterval: 1,
title: {
text: 'Total alarmas'
},
allowDecimals: false,
min: 0
},
series : data,
});
});
Image explicative:
Thank you very much in advance!!!
EDIT & SOLVED! ...Thanks Jerko again! ...see below answers for the solution!
This is the common problem with columns and bars in Highcharts. You need to add pointRange under the plotOptions
Also tickInterval for one day is 24*3600*1000 not 1 (x-axis is in microseconds)
here is working fiddle
http://jsfiddle.net/nah67/3/
plotOptions: {
series: {
pointRange: 24 * 3600 * 1000 // one day
}
}
P.S. I removed some comments from your code, because they were distracting me :)

Categories

Resources