Heatmap values are lapsing in Highcharts - javascript

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

Related

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

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

How to remove bullet from tooltip when using highchart?

I am working on column chart using Highchart. My chart is working fine. I just want to remove bullet showing in tooltip. From image you can see the bullet appears before the Amount. How can I remove this? Please share with me if anyone has any idea.
My Codes are below:
Jsfiddle link
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="hist" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
$(document).ready(function() {
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
// comma separation
Highcharts.numberFormat = function (number, decimals, decimalPoint, thousandsSep) {
number = +number || 0;
decimals = +decimals;
var lang = Highcharts.getOptions().lang,
origDec = (number.toString().split('.')[1] || '').length,
decimalComponent,
strinteger,
thousands,
absNumber = Math.abs(number),
ret;
if (decimals === -1) {
decimals = Math.min(origDec, 20); // Preserve decimals. Not huge numbers (#3793).
} else if (!isNumber(decimals)) {
decimals = 2;
}
// A string containing the positive integer component of the number
strinteger = String(Highcharts.pInt(absNumber.toFixed(decimals)));
// Leftover after grouping into thousands. Can be 0, 1 or 3.
thousands = strinteger.length > 3 ? (strinteger.length - 1) % 2 : 0;
// Language
decimalPoint = Highcharts.pick(decimalPoint, lang.decimalPoint);
thousandsSep = Highcharts.pick(thousandsSep, lang.thousandsSep);
// Start building the return
ret = number < 0 ? '-' : '';
// Add the leftover after grouping into thousands. For example, in the number 42 000 000,
// this line adds 42.
ret += thousands ? strinteger.substr(0, thousands) + thousandsSep : '';
// Add the remaining thousands groups, joined by the thousands separator
ret += strinteger.substr(thousands).replace(/(\d{2})(?=\d{3})/g, '$1' + thousandsSep);
// Add the decimal point and the decimal component
if (decimals) {
// Get the decimal component, and add power to avoid rounding errors with float numbers (#4573)
decimalComponent = Math.abs(absNumber - strinteger + Math.pow(10, -Math.max(decimals, origDec) - 1));
ret += decimalPoint + decimalComponent.toFixed(decimals).slice(2);
}
return ret;
};
$('#hist').highcharts({
credits: { enabled: false },
exporting: { enabled: false },
chart: {
type: 'column',
backgroundColor: "transparent",
plotBorderColor: '#ccc',
plotBorderWidth: 1,
borderWidth: 2,
borderColor: '#ccc',
/*borderRadius: 10,*/
shadow: true,
spacingBottom: 30,
spacingTop: 30,
spacingLeft: 30,
spacingRight: 30
},
title: {
text: 'Title here'
},
xAxis: {
title: {text: "Rate",
style: {
fontWeight: 'bold',
fontSize:'14px'
} },
categories: [
'ABC Percentage: 10.81%',
'CDE: 18.15%'
],
labels: {
style: {
fontWeight: 'bold',
fontSize:'14px'
}
},
crosshair: false
},
yAxis: {
min: 0,
max: 1800000,
title: {
text: 'Amount (Rs.)'
},
labels: {
formatter: function () {
return this.value/100000 + "L";
}
}
},
tooltip: {
headerFormat: '<b>Rate<br>{point.key}<br></b>',
//pointFormat: '',
//footerFormat: '<b>{point.key}</b>',
//shared: true,
useHTML: true,
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
showInLegend: false,
name: '<b>Amount (Rs.)</b>',
data: [1070452, 1942379]
}]
});
});
Use formatter function as per code below :
useHTML: true,
formatter: function () {
return '<b>Rate</b><br/>'+this.point.category +'<br><b>'+this.series.name+'</b> '+ this.y ;
}
See your fiddle updated here
You can remove the bullet by changing the appearace of the tooltip/tooltip format.
Tooltip format

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/

Highchart: is it possible to change the font of the label in Highchart via a click of a button?

Link to JFiddle: http://jsfiddle.net/z24ysp8m/3/
Here is the code in concern:
$(function() {
var chartData = [-5, 5, -10, -20];
var timeStamps = [];
var index = 1;
var pWidth = 25;
$('#b').click(function(){
timeStamps.push(new Date());
var buttonB = document.getElementById('b');
buttonB.disabled = true;
/* if(index == 1){
$('#container').highcharts().xAxis[0].labels.style = {"color":"#6D869F","fontWeight":"bold"};
}*/
if(index <= chartData.length){
$('#container').highcharts().series[0].remove();
$('#container').highcharts().addSeries({pointPlacement: 'on', data: [chartData[index - 1]],
pointWidth: pWidth});
$('#container').highcharts().xAxis[0].setCategories([index]);
setTimeout(function(){index++;}, 2000);
}
if(index < chartData.length){
setTimeout(function(){buttonB.disabled = false;}, 1500);
}else{
setTimeout(function(){buttonB.style.visibility="hidden";}, 1500);
}
if(index == chartData.length - 1){
setTimeout(function(){document.getElementById('b').innerHTML = 'Lasst Period';}, 1500);
}
console.log(timeStamps);
})
// $(document).ready(function () {
Highcharts.setOptions({
lang: {
decimalPoint: ','
},
});
$('#container').highcharts({
chart: {
type: 'column',
width: 170,
marginLeft: 74,
marginRight: 16,
marginBottom: 60
},
title: {
text: ''
},
colors: [
'#0000ff',
],
xAxis: {
title: {
text: ''
// offset: 23
},
gridLineWidth: 1,
startOnTick: true,
tickPixelInterval: 80,
categories: ['Filler'], // used only to make sure that the x-axis of the two charts
// are aligned, not shown on the chart via setting the font color to white
min:0,
max:0,
labels: {
style: {
color: 'white'
}
}
},
yAxis: {
title: {
text: 'Value'
},
min: -20,
max: 20,
tickPixelInterval: 40
},
plotOptions: {
series: {
animation: {
duration: 1000
}
}
},
credits: {
enabled: false
},
tooltip: {
formatter: function () {
return Highcharts.numberFormat(this.y, 2) + '%';
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
data: [],
pointWidth: pWidth
}]
});
// });
});
I want that the x-axis has no label when the page is loaded (The reason why I added in a filler text with white font is due to the fact that I don't want the size of the chart change upon click of a button). And upon the click of button, the label should be consecutively 1, 2, 3, 4...
Is there anyway around it except for setting marginBottom (which is not very precise)?
You may use .css() method for changing fill color of your text label.
Here you can find information about this method:
http://api.highcharts.com/highcharts#Element.css
Highcharts.each($('#container').highcharts().xAxis[0].labelGroup.element.children, function(p, i) {
$(p).css({
fill: 'red'
});
});
And here you can find simple example how it can work:
http://jsfiddle.net/z24ysp8m/6/

Highcharts : yAxis, values rounded to a maximum of two decimal places

The code of my graph is this (take data from a php page and then adds some series):
$('#grafico_1').highcharts({
chart: {
type: 'line',
zoomType: 'xy',
animation : false,
events: {
selection: function(event) {
if(event.resetSelection){
setTimeout(function(e){
var chart = $('#grafico_1').highcharts();
var extreme = chart.yAxis[0].getExtremes();
var mio_min = parseFloat(proprieta_temperatura_aperto[34]);
var mio_max = parseFloat(proprieta_temperatura_aperto[35]);
if(extreme.dataMin < mio_min){
mio_min = extreme.dataMin;
}
if(extreme.dataMax > mio_max){
mio_max = extreme.dataMax;
}
chart.yAxis[0].setExtremes(mio_min,mio_max);
$("#temperatura_min_max_rilevato").html("Min "+extreme.dataMin+"°C - Max "+extreme.dataMax+"°C");
//console.log("zoom - ");
}, 10);
}else{
setTimeout(function(e){
var chart = $('#grafico_1').highcharts();
var extreme = chart.yAxis[0].getExtremes();
$("#temperatura_min_max_rilevato").html("Min "+extreme.dataMin+"°C - Max "+extreme.dataMax+"°C");
//console.log("zoom + "+JSON.stringify(extreme));
}, 50);
}
}
},
},
credits : {
enabled : false
},
title: {
text: 'Grafico di Oggi'
},
xAxis: {
type: 'datetime',
title: {
text: false
}
},
yAxis: [
{
title: {
text: false
},
labels: {
format: '{value}°C',
},
//ceiling : parseFloat(proprieta_temperatura_aperto[35]),
//floor: parseFloat(proprieta_temperatura_aperto[34]),
max : parseFloat(proprieta_temperatura_aperto[35]),
min: parseFloat(proprieta_temperatura_aperto[34]),
},
{
title: {
text: false
},
min: 0,
max : 1,
ceiling:1,
floor : 0,
//tickLength : 1,
opposite: true,
tickInterval: 1,
labels: {
formatter: function() {
if (this.value == 0 || this.value == 1){
return this.value;
}else{
return null;
}
}
}
}
],
tooltip: {
formatter: function() {
var s = '<b>Data</b> '+Highcharts.dateFormat('%H:%M:%S', this.x) + '<br><b>Temperatura</b> ' + this.y + '°C<br/>';
$.each(this.points, function(i, point) {
if(point.series.name != "Temperatura"){
s += '<b>' + point.series.name +'</b> : '+ point.y + '<br>';
}
});
return s;
},
shared: true,
backgroundColor: '#FCFFC5'
},
plotOptions: {
line : {
turboThreshold: 0,
},
series: {
animation: false,
marker: {
enabled: false
}
}
},
series: []
});
the problem occurs when run one (or more) zoom on the graphs , and on the y-axis the values ​​are listed with more than two decimal places. I would like to limit to two the maximum number of decimal places.
I think i have to change this field (format)
yAxis: [
{
labels: {
format: '{value}°C',
},
but I do not know how.
Try to write the value as {value:.2f}, as proposed here: link

Categories

Resources