Highcharts set xAxis values starting 12am and ends in 11pm - javascript

I'm using a highcharts plugin, my aim is to draw a graph for the wholeday by hour.
How to set the xAxis to use 12hour format (w/ AM&PM), start => end of the day. Or some option to have 3hours interval.
For example i have filter for today & yesterday
My Data, looks like this (timestamp & value):
[ [1561593600000, 102.5], [1561658400000, 177.45] ]
Heres my full script:
$(function(){
var moneySign = "$";
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
// Sales Chart
var SalesChart = Highcharts.chart('ba-chart-sales', {
title: { text: '' },
exporting: { enabled: false },
subtitle: { text: '' },
yAxis: {
title: { text: '' },
useHTML: true,
labels: {
formatter: function() {
return moneySign + this.axis.defaultLabelFormatter.call({
axis: this.axis,
value: this.value
});
}
}
},
xAxis: {
// Default for 7days & 30days (will change for today||yesterday)
type: 'datetime',
dateTimeLabelFormats: { day: '%b %e' },
tickInterval: 24 * 3600 * 1000 // interval of 1 day
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
enabled:false
},
tooltip: {
dateTimeLabelFormats: { day: '%B %e, %Y' },
shared: true,
useHTML: true,
headerFormat: '{point.key}<div>',
pointFormat: '<div style="background-color: #0549d1; height: 10px; width: 10px; border-radius: 50%; display: inline-block;"></div>' +
'<div style="margin-left: 5px; margin-top: 8px; width:30px; display: inline-block;"><b> ' + moneySign + '{point.y}</b></div>',
footerFormat: '</div>',
crosshairs: {
color: '#ccc',
className: 'chart-crosshair',
dashStyle: 'solid',
width: 1
}
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
marker: {
enabled: false,
symbol: 'circle'
}
}
},
series: [{
tooltip: { xDateFormat: '%B %e, %Y' },
showInLegend: false,
name: '',
data: []
}],
responsive: rules: [{
condition: {
maxWidth: 600
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}],
credits: { enabled: false }
});
// Initial
var SalesChartExtremes = SalesChart.yAxis[0].getExtremes();
// Change Cart Type `line` || `column`
function reDrawChart(filter, chart) {
var series = SalesChart.series[0];
var newType = ['today', 'yesterday'].includes(filter) ? 'column' : 'line';
series.chart.addSeries({
type: newType,
name: series.name,
color: series.color,
data: series.options.data,
}, false);
series.remove();
}
// Get Offer Analytics Data
function getAnalytics(filter=''){
$.ajax({
type: "GET",
url: "<%= analytics_url %>",
data: {chart_filter: filter},
dataType: "JSON",
success: function(data){
var todayLocalDate = "<%= #local_time.strftime("%Y-%m-%d") %>".split('-').map(Number);
var yesterdayLocalDate = "<%= #local_time.yesterday.strftime("%Y-%m-%d") %>".split('-').map(Number);
if( ['30', '7', ''].includes(filter) ){
var toolTipProp = { xDateFormat: '%B %e, %Y' };
var pointIntervalProp = 24 * 3600 * 1000; // one day
var pointStartProp = '';
var chartType = 'line';
}else{
if (filter == 'today'){
var pointStartProp = Date.UTC(todayLocalDate[0], todayLocalDate[1], todayLocalDate[2]);
}else if (filter == 'yesterday'){
var pointStartProp = Date.UTC(yesterdayLocalDate[0], yesterdayLocalDate[1], yesterdayLocalDate[2]);
}
var toolTipProp = { xDateFormat: '%B %e, %Y %I:%M%p' };
var pointIntervalProp = 3600000 * 3; // 3 hours
var chartType = 'column';
}
var markerEnabled = data.sales.length == 1
var salesOpts = {
tooltip: toolTipProp,
data: data.sales,
animation: { duration: 1000 },
pointInterval: pointIntervalProp,
pointStart: pointStartProp,
crosshair: true,
marker: {
enabled: markerEnabled
}
}
// Sets yAxis min & max values for empty result
if(data.sales.length == 0){
SalesChart.yAxis[0].setExtremes(0,100);
SalesChart.yAxis[0].update({tickInterval: 20});
}else{
// return to previous categories based on data
SalesChart.yAxis[0].setExtremes(SalesChartExtremes.min, SalesChartExtremes.max);
SalesChart.yAxis[0].update({tickInterval: 500});
}
if(filter == 'today' || filter == 'yesterday'){
var defaultTimeOpt = {
tickInterval: 1,
type: 'datetime',
dateTimeLabelFormats: {
millisecond: '%l:%M:%S.%L %P',
second: '%l:%M:%S %P',
minute: '%l:%M %P',
hour: '%l:%M %P',
day: '(%e. %b) %l:%M %P'
}
}
SalesChart.xAxis[0].update(defaultTimeOpt, true);
}else{
// return to day options
var defaultDayOpt = {
type: 'datetime',
dateTimeLabelFormats: { day: '%b %e' },
tickInterval: 24 * 3600 * 1000 // interval of 1 day
}
SalesChart.xAxis[0].update(defaultDayOpt, false);
}
SalesChart.series[0].update(salesOpts, true);
reDrawChart(filter, 'sales');
},
error: function(data) {
flashError("Error getting analytics");
}
});
return false;
}
});
// Call getAnalytics when select dropdown filter change (e.g. today, yesterday, lastweek ...)
getAnalytics();
Current progress,
TODO 1: If only have few data, the time where NO data should have 0 value (so there's still progress in chart).
TODO 2: Set the time/hour in xAxis & have an option for hour gap/interval like 3hours ... 12AM, 3AM, 6AM ....

If you already have the value then you can do something like
xAxis: {
labels: {
//isPm() is a function that checks for am and pm of your timestamp
format: '{value} ' + (isPm() ? "pm":"am")
}
}
also you need to show how you are plotting the chart so as to know the best way of implementation

You can change your datetime label format (API):
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
millisecond: '%l:%M:%S.%L %P',
second: '%l:%M:%S %P',
minute: '%l:%M %P',
hour: '%l:%M %P',
day: '(%e. %b) %l:%M %P',
}
}
See this JSFiddle demonstration.
The values set in dateTimeLabelFormats is a subset of PHPs strftime. In this case:
%l: Hour in 12-hour format, with a space preceding single digits. 1 through 12
%P: Lower-case 'am' or 'pm' based on the given time. Example: am for 00:31, pm for 22:23

Related

One y axis data point there but it's x axis data point missing in weekly chart

Here below code plase any look if they know thank you.
In it 1 weeks (5 day) data points excluding saturday and sunday but x
axis 1 days (21 may) data point missing.
2 seris of data both series contain date and price in itlike share price value for that day
In attachment all x data point showing but all not distributed equally i don,t want like this img
var series_a = [{"close":1814,"date":"2021\/05\/19"},{"close":1772,"date":"2021\/05\/20"},{"close":1752,"date":"2021\/05\/21"},{"close":1793,"date":"2021\/05\/24"},{"close":1817,"date":"2021\/05\/25"},{"close":1850,"date":"2021\/05\/26"}];
var series_b = [{"close":1764,"date":"2021\/05\/19"},{"close":1752,"date":"2021\/05\/20"},{"close":1787,"date":"2021\/05\/21"},{"close":1791,"date":"2021\/05\/24"},{"close":1790,"date":"2021\/05\/25"},{"close":1804,"date":"2021\/05\/26"}];
tickDataPoint = series_b.map(function(e) {
return new Date(e.date).getTime()
});
series_a = series_a.map(function(e) {
return [new Date(e.date).getTime(), e.close, ]
});
series_b = series_b.map(function(e) {
return [new Date(e.date).getTime(), e.close, ]
});
const timezone = new Date().getTimezoneOffset()
Highcharts.setOptions({
global: {
timezoneOffset: timezone
}
});
var a = Highcharts.stockChart('dips_stock_div_aptech', {
chart: {
width: 790,
height: 280,
},
scrollbar: {
enabled: false
},
yAxis: {
opposite: false,
},
credits: {
enabled: false
},
plotOptions: {
// line: {
// dataLabels: {
// enabled: true
// },
// enableMouseTracking: false
// // }
// series: {
// gapSize: 12
// }
},
xAxis: {
// ordinal:true,
type: 'datetime',
// gridLineWidth: 1,
// tickInterval: null,
// step: 1,
// alignTicks:true,
tickInterval: 1 , // 2 month
// tickWidth:0,
// categories: tickDataPoint, tickInterval: 1,
breaks: [{
from: 1621535400000,
to: 1621708200000,
// breakSize: 1
}],
labels: {
formatter: function () {
// return Highcharts.dateFormat('%m-%e-%Y', this.value)
const index = tickDataPoint.findIndex(tickDataPoint => tickDataPoint == this.value);
console.log(tickDataPoint+'-------'+this.value); // 3
console.log(index); // 3
if (index>=0){
return Highcharts.dateFormat('%e\'%b', this.value);
}else{
return '';
}
}
}
},
rangeSelector: {
enabled: false
},
legend: {
enabled: false
},
series: [{
name: "Astral Ltd",
data: series_a,
},
{
name: "BSE Sensex",
data: series_b,
}
],
navigator: {
enabled: false
},
});
<HTML>
<BODY bgcolor="#FFFFFF">
<div id="dips_stock_div_aptech" style="overflow: visible;width:100%;margin:10px;margin-top: -5px;"></div>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
</BODY>
</HTML>
[![in img all data points showing but x data point not distributed equally date 22 and 23 may taking long space][1]][1]

How to change UTC timestamp on the Highstock charts?

I have an API at https://gmlews.com/api/data. And my code for highstock charts in http://jsfiddle.net/estri012/b5nhezLs/8/ .
My problem is my timestamp look like this "2020-03-15T11:46:10+07:00". So on the chart it should shows 15 March 11:46 instead of 15 March 04:46. But the chart show UTC time. How to fix it, so the chart show the local same time with mine? And the last three data on the chart show 18 March instead of 19 March. In my API, the last three data must be 19 March not 18 March.
$(function () {
$.getJSON('https://gmlews.com/api/data', function (data) {
console.log(data);
function format_two_digits(n) {
return n < 10 ? '0' + n : n;
}
var accelero_x = [], timestamp = [];
for (var i=0; i<data.length; i++){
let inArr = [];
inArr.push(Date.parse(data[i].timestamp));
inArr.push(data[i].accelero_x);
accelero_x.push(inArr);
timestamp.push(data[i].timestamp);
}
console.log(accelero_x);
console.log(timestamp);
// Create the chart
window.chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
inputEnabled: true,
buttons: [{
type: 'day',
count: 1,
text: '1D',
},
{
type: 'week',
count: 1,
text: '1W',
},
{
type: 'month',
count: 1,
text: '1M',
},
{
type: 'year',
count: 1,
text: '1Y',
}, {
type: 'all',
count: 1,
text: 'All',
}],
inputDateFormat: '%d-%m-%Y',
inputDateParser: function (value) {
value = value.split('-');
return Date.UTC(
parseInt(value[2]),
parseInt(value[1]) - 1,
parseInt(value[0])
);
},
},
title: {
text: 'Accelero X'
},
xAxis: {
type: "datetime",
labels: {
/* format: '{value:%Y-%m-%d}', */
formatter: (currData) => {
const currDate = new Date(currData.value);
return format_two_digits(currDate.getHours()) + ':' + format_two_digits(currDate.getMinutes());
},
rotation: 45,
align: 'left'
}
},
series: [{
name: 'Accelero X',
data: accelero_x,
type: 'spline',
tooltip: {
valueDecimals: 2
}
}]
}, function (chart) {
// apply the date pickers
setTimeout(function () {
$('input.highcharts-range-selector', $('#' + chart.options.chart.renderTo)).datepicker();
}, 0)
});
});
// Set the datepicker's date format
$.datepicker.setDefaults({
dateFormat: 'dd-mm-yy',
beforeShow: function() {
var date = $(this).val().split('-');
$('input.highcharts-range-selector').datepicker("setDate", new Date(parseFloat(date[0]), parseFloat(date[1]) - 1, parseFloat(date[2])));
},
onSelect: function (dateText) {
this.onchange();
this.onblur();
}
});
});
Try to set time.useUTC to false - https://api.highcharts.com/highcharts/time.useUTC
Demo: http://jsfiddle.net/BlackLabel/avhw7km8/
time: {
useUTC: false
},

not able ot show date in x axis in highcharts

i want to show date in x asis but not able to show. showing values like this 00.00.00.100 in the graph.unable to convert 1577844000000 to proper date,month,year in javascript to show in the x axis using dateTimeLabelFormats in highcharts.how to use ticks and how to show it in graphs.
ticks values are printing in the console like this.
sample tick data
1577844000000
1577843100000
1577842200000
1577841300000
15778404000
sample data from the response
DeviceTimeStamp: "2020-01-10T00:30:00"
code
getalldata();
function getalldata() {
var xhttp_roomlogs = new XMLHttpRequest();
xhttp_roomlogs.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp_roomlogs.responseText);
var Ch1Temp = [];
var Ch2Temp = [];
$(response).each(function (i, item) {
var date = UtcToIst(item.DeviceTimeStamp);
var ticks = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
Ch1Temp.push([ticks, item.Ch1Temp])
Ch2Temp.push([ticks, item.Ch2Temp])//
});
$('#container').empty();
var labels = response.map(function (e) {
var roomtempdata = e.Ch1Temp;
return parseFloat(roomtempdata);
})
var ch2temp = response.map(function (e) {
var roomtempdata = e.Ch2Temp;
return parseFloat(roomtempdata);
})
Highcharts.chart('container', {
credits: {
enabled: false
},
title: {
text: 'Chamber 1 & 2 Temp'
},
subtitle: {
text: 'in Degree Celcius'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Temperature'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
//y co-ordinates
series: [{
name: 'Chamber 1 Temp',
data: labels
},
{
name: 'Chamber 2 Temp',
data: ch2temp
}
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
//highcharts end
}
};
xhttp_roomlogs.open("GET", "/api/data", true);
xhttp_roomlogs.send();
}
function UtcToIst(data) {
var dt = new Date(data);
return dt;
}
You can convert the json date using:
var jsonDate = "\/Date(1577844000000)\/".substr(6);
var dateObject = new Date(parseInt(jsonDate ));
var stringDate = (dateObject.getMonth() + 1) + "/" + dateObject.getDate() + "/" + dateObject.getFullYear();
console.log("Dat Object:" + dateObject);
console.log("String Date:" + stringDate);
sample hightchart code:
Highcharts.chart('container', {
chart: {
type: 'column'
},
xAxis: {
categories: ['1/1/2020', '1/2/2020', '1/3/2020', '1/4/2020', '1/5/2020']
},
plotOptions: {
column: {
stacking: 'normal'
}
},
legend: {
labelFormatter: function () {
if(this.data.length > 0) {
return this.data[0].category;
} else {
return this.name;
}
}
},
series: [{
data: [{x:0,y:1}],
name: '1/1/2020'
},{
data: [{x:1,y:1}],
name: '1/2/2020'
},{
data: [{x:2,y:1}],
name: '1/3/2020'
},{
data: [{x:3,y:1}],
name: '1/4/2020'
},{
data: [{x:4,y:1}],
name: '1/5/2020'
}]
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<figure class="highcharts-figure">
<div id="container"></div>
</figure>

Heatmap values are lapsing in Highcharts

I'm using latest version (7.0.1) of Highcharts API. I want to see my datas on Highcharts heatmap. After I set my datas, everything is working nicely except that when I hover over datas, it is shown 3 point further left values in tooltip and hover effect is not working. I am also showing date and time in that tooltip and they are correct. So the problem is with values.
When I change boostThreshold and turboThreshold values, deactive them, I see true values and hover effect start working but after change my mouse position hover effect is staying and changing its orginal color. And I try to disable hover effect and it is not working too.
In the example heatmap the value should have been 66
This is how I initialize the heatmap.
heatmap = Highcharts.chart('heatmap', {
chart: {
backgroundColor: '#FBFCFD',
type: 'heatmap',
inverted: true
},
boost: {
useGPUTranslations: true
},
title: {
text: 'Aktif Tüketim Haritası',
margin: 5,
style: {"font-family": "titillium_websemibold"}
},
xAxis: {
endOnTick: true,
startOnTick: true,
type: 'datetime',
tickPixelInterval: 30,
labels: {
format: '{value:%d %B}'
},
reversed: false
},
plotOptions: {
heatmap: {
states: {
hover: {
enabled: false
}
}
}
},
yAxis: {
title: {
text: null
},
minPadding: 0,
maxPadding: 0,
min: 0.0,
max: 23.0
},
colorAxis: {
stops: [
[0, 'white'],
[0.25, 'YellowGreen'],
[0.50, 'yellow'],
[0.75, 'DarkOrange'],
[1, 'Maroon']
/*[0, '#3060cf'],
[0.5, '#fffbbc'],
[0.9, '#c4463a'],
[1, '#c4463a']*/
],
labels: {
format: '{value} kVA'
}
},
legend: {
symbolWidth: 550
},
exporting: {enabled: false},
series: [{
states: {
hover: {
enabled: false
}
},
boostThreshold: 100,
turboThreshold: Number.MAX_VALUE,
borderWidth: 0,
nullColor: '#EFEFEF',
colsize: 24 * 36e5, // one day
tooltip: {
headerFormat: 'Aktif Tüketim<br/>',
pointFormatter: function () {
var decs = this.y.toString().split(".");
var minute;
if (!decs[1]) {
minute = '00';
} else {
minute = Math.round(parseInt(decs[1].padEnd(2, "0")) * 60 / 100);
minute = minute.toString().padStart(2, "0");
}
var real = decs[0] + ':' + minute;
return Highcharts.dateFormat('%e %b, %Y', new Date(this.x)) + ':' + real + ':<b>' + this.value + '</b> kVA ';
},
}
}]
});
Thanks in advance!
code in jsfiddle
The tooltip has strange behavior because you haven't set rowsize which is equal to 1 by default. Check demo posted below.
Code:
series: [{
//boostThreshold: 100,
turboThreshold: Number.MAX_VALUE,
borderWidth: 0,
nullColor: '#EFEFEF',
colsize: 24 * 36e5, // one day
rowsize: 0.1666666666,
tooltip: {
headerFormat: 'Aktif Tüketim<br/>',
pointFormatter: function() {
var decs = this.y.toString().split(".");
var minute;
if (!decs[1]) {
minute = '00';
} else {
minute = Math.round(parseInt(decs[1].padEnd(2, "0")) * 60 / 100);
minute = minute.toString().padStart(2, "0");
}
var real = decs[0] + ':' + minute;
return Highcharts.dateFormat('%e %b, %Y', new Date(this.x)) + ':' + real + ':<b>' + this.value + '</b> kVA ';
}
}
}]
Demo:
https://jsfiddle.net/BlackLabel/6jufyeb8/1/
API reference:
https://api.highcharts.com/highcharts/series.heatmap.rowsize

Filter categories in highcharts by using checkboxes

I would like to filter the categories by using the checkboxes. For example, if the user checks Server - only Categories belonging to class Server should be visible and redraw the highchart.
Like this:
And if the user checks all checkboxes, all categories should be visible.
Here is the fiddle: http://jsfiddle.net/Lqcrgrbh/
Thanks in advance!
$(function() {
var chart = new Highcharts.Chart('container', {
chart: {
type: 'columnrange',
inverted: true,
height: 100
},
title: {
text: null
},
xAxis: {
categories: [{"name":"Email","sys_class":"Business Service"},{"name":"Server","sys_class":"Server"}],
labels: {
formatter: function () {
return this.value.name;
},
useHTML: true
}
},
yAxis: {
type: 'datetime',
tickInterval: 1000 * 60 * 60 * 24 * 30 * 6,
title: {
text: null
},
labels: {
formatter: function () {
return Highcharts.dateFormat('%b %Y', this.value);
}
}
},
plotOptions: {
series: {
grouping: false,
stacking: 'normal',
pointPadding: 0,
groupPadding: 0.0,
allowPointSelect: true,
dataLabels: {
enabled: true,
align: 'center',
x: -10,
formatter: function() {
return this.series.name;
}
}
}
},
tooltip: {
formatter: function() {
var categories = this.x.name,
series_name = this.series.name,
low = this.point.low,
high = this.point.high,
duration = high - low;
return '<b>' +series_name + '</b><br/><b>'+ categories + ': </b>'+ Highcharts.dateFormat('%d %b %Y',
new Date(low)) + " - " + Highcharts.dateFormat('%d %b %Y',
new Date(high)) + '<br/><b>Duration: </b>' + parseInt(duration / (1000 * 60 * 60 * 24 * 365)) + " years, " + new Date(duration).getUTCMonth() + " months, " + new Date(duration).getUTCDate() + " days";
}
},
legend: {
enabled: false
},
series: [{"color":"#f47700","data":[[],[1475539200000,1570147200000]],"name":"Concept"},{"color":"#f43701","data":[[1475625600000,1570233600000],[]],"name":"Planing"}]
});
});
You should be able to edit your togglePointsByClass method so you will not hide your series, but you will change extremes on your xAxis. In this case you can use Axis.update() method.
function togglePointsByClass(className, shouldShow, chart) {
var isChartDirty = false;
if (shouldShow) {
chart.xAxis[0].userOptions.categories.forEach(function(category, i) {
if (category.class === className) {
visibleArr.push(i);
}
});
} else {
chart.xAxis[0].userOptions.categories.forEach(function(category, i) {
if (category.class === className && visibleArr.indexOf(i) > -1) {
visibleArr.splice(visibleArr.indexOf(i), 1);
}
});
}
if (visibleArr.length) {
chart.xAxis[0].update({
min: Math.min.apply(null, visibleArr),
max: Math.max.apply(null, visibleArr)
})
}
}
Here you can see simple example how it can work: http://jsfiddle.net/Lqcrgrbh/1/

Categories

Resources