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

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

Related

Highcharts bar with negative stack: how to show different tooltip for left and right

i am using highcharts bar with negative stack, problem is when i hover over the left side of the chart that is in red color it shows the correct disease name that is "TB Suspect" but when i hover over the blue bar it shows the same "TB Suspect" disease which is wrong, it should show "Otitis Media"
same problem for all other diseases
Here is the code
<script>
$(function () {
if($('#disease-bar').length > 0){
// Age categories
var categories_c = [<?=$comm_disease_title?$comm_disease_title:0;?>];
var categories_nc = [<?=$non_comm_disease_title?$non_comm_disease_title:0;?>];
$(document).ready(function () {
$('#disease-bar').highcharts({
colors: ['#dd4c39', '#00a9e9', '#c61a7e', '#bd8030', '#949293', '#075290', '#7db6ed', '#009451', '#c84433'],
chart: {
type: 'bar',
backgroundColor: null
},
title: {
text: 'Top Five Communicable & Non-communicable Diseases'
},
xAxis: [{
categories: categories_c,
reversed: false,
crosshair: true,
labels: {
step: 1
}
}, { // mirror axis on right side
opposite: true,
reversed: false,
categories: categories_nc,
linkedTo: 0,
labels: {
step: 1
}
}],
yAxis: {
title: {
text: null
},
labels: {
formatter: function() {
var s = Math.abs(this.value);
if (s.toFixed(0) >= 1000000) {
return s.toFixed(0) / 1000000 + 'M';
} else {
return s.toFixed(0) / 1000 + 'K';
}
}
}
},
plotOptions: {
series: {
cursor: 'pointer',
stacking: 'normal',
//point: {
events: {
click: function () {
//alert(this.name);return;
if(this.name=="Communicable"){
var url = 'disease.php<?=$next_url;?>&module=1';
}
else {
var url = 'disease.php<?=$next_url;?>&module=2';
}
//alert(url);
location.href = url;
}
,legendItemClick: function (event) {
//console.log(event.target.visible);
if(event.target.name=='Communicable'){
if(event.target.visible){this.chart.xAxis[0].update({
labels: {
enabled: false
}
});}
else {this.chart.xAxis[0].update({
labels: {
enabled: true
}
});}
}
else {
if(event.target.visible){this.chart.xAxis[1].update({
labels: {
enabled: false
}
});}
else {this.chart.xAxis[1].update({
labels: {
enabled: true
}
});}
}
//console.log(event.target.name);
//console.log(this.chart.xAxis[0]);
}
}
// }
}
},
tooltip: {{
formatter: function () {
return '<b>' + this.point.category + '</b><br/>' +
'Diseases: <b>' + Math.abs(this.point.y) +'</b>';
}
},
exporting: {
//enabled: false
},
credits: {
enabled: false
},
series: [{
name: 'Communicable',
data: [<?=$comm_disease_value?$comm_disease_value:0;?>]
}, {
name: 'Non-communicable',
data: [<?=$non_comm_disease_value?$non_comm_disease_value:0;?>]
}]
});
});
}
});
</script>
Here is the tooltip code which i am using
tooltip: {{
formatter: function () {
return '<b>' + this.point.category + '</b><br/>' +
'Diseases: <b>' + Math.abs(this.point.y) +'</b>';
}
},
JS Fiddle : https://jsfiddle.net/hamza9/h1nrn9nu/
I was able to get the correct category from the formatter:
formatter: function() {
var subCategoryLabel = this.series.chart.xAxis[this.series._i]
.categories[this.point.index];
return '<b>' + subCategoryLabel + '</b><br/>' +
'Diseases: <b>' + Math.abs(this.point.y) + '</b>';
}
You have to modify series data as array of object, wheredd is respective categories name and y is the value
series: [{
name: 'Communicable',
data: [{y:-1489599,dd:'Acute (Upper) Respiratory Infections'}, {y:-256548,dd:'Scabies'}, {y:-157531,dd:'Diarrhoea / Dysentery < 5 yrs'}, {y:-148696,dd:'Diarrhoea / Dysentery > 5 yrs'}, {y:-86283,dd:'Worm Infestations'}]
//url: 'disease.php?frequency=m&year=2017&month=1&quarter=&fatype=&disease_cat=comm'
}, {
name: 'Non-communicable',
data: [{y:399786,dd:'Fever due to other causes'}, {y:247500,dd:'Peptic Ulcer Diseases'}, {y:196653,dd:'Hypertension'}, {y:176866,dd:'Dental Caries'}, {y:169514,dd:'Diabetes Mellitus'}]
//url: 'disease.php?frequency=m&year=2017&month=1&quarter=&fatype=&disease_cat=noncomm'
}]
In your tooltip you can access it via the "point" attribute of the object passed in:
tooltip: {
formatter: function() {
return '<b>' + this.point.dd + '</b><br/>' +
'Diseases: <b>' + Math.abs(this.point.y) + '</b>';
}
},
Fiddle demo
Simply get rid of the linkedTo property from the second xAxis and link 'Non-Communicable' series to 1 xAxis.
API Reference:
http://api.highcharts.com/highcharts/series%3Cbar%3E.xAxis
Example:
https://jsfiddle.net/yqe0kunn/

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/

Highcharts Bar Chart: possible to combine datapoints inside dataLabels?

I have a Highcharts horizontal bar chart with two series. Is it possible to combine the grouped data points into each data label so that they appear together, e.g. 1.00 / 2.3?
CODE:
var labels = [
'AAA/Aaa',
'AA+/Aa1',
'AA/Aa2',
'AA-/Aa3',
'A+/A1',
'A/A2',
'A-/A3'
];
var theData = [
{
name: 'Company 1',
data: [0.576,7.617,12.101,18.839,18.022,7.644,9.72]
},
{
name: 'Company 2',
data: [4.123,12.862,14.561,13.754,12.226,11.135,7.51]
}
];
HIGHCHARTS CONFIG:
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
legend: {
align: 'center',
layout: 'horizontal',
verticalAlign: 'bottom'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
formatter: function() {
var out = '<span class="col-chart-label">';
out += this.y + ' / ' + this.y;
out += '</span>'
return out;
},
useHTML: true
}
}
},
series: theData,
tooltip: {
enabled: false
},
xAxis: {
categories: labels,
labels: {
formatter: false,
overflow: 'justify',
rotation: false
},
reversed: true
}
});
});
The demo is here:
http://jsfiddle.net/dylanmac/RungW/2/
To reiterate, there should be one data label per pair of bars with the top bar as the first value and the bottom bar as the second value, separated by "/"
Thanks a lot.
You can loop through all series and sum values for a specific category, see: http://jsfiddle.net/RungW/3/
formatter: function() {
var out = '<span class="col-chart-label">',
series = this.point.series.chart.series,
p1 = series[0].yData[this.point.x],
p2 = series[1].yData[this.point.x];
out += this.y + ' / ' + (p1 + p2);
out += '</span>'
return out;
},

addPoint using highcharts (javascript)

I have started working with highcharts.js, but fails to add new points my bar graph:
Every time it goes into addPoint, Firefox freezes :(
I am using Firebug, and when it tries to addPoint, it always freeze :(
// if no graph
if (! charts[0])
{
// make chart table
var round_ids = [];
var total_players = [];
var total_bets = [];
$.each(last_rounds_cache.last_rounds_data, function(index, value)
{
round_ids.push(Number(value[0]));
total_players.push(Number(value[2]));
total_bets.push(Number(value[3]));
}
)
charts[0] = new Highcharts.Chart({
chart: {
renderTo: 'players_per_round',
type: 'column',
events: {
click: function(e) {
// find the clicked values and the series
var x = e.xAxis[0].value,
y = e.yAxis[0].value,
series = this.series[0];
// Add it
series.addPoint([x, y]);
}
}
},
title: {
text: 'Players/Bets per Round'
},
xAxis: {
categories: round_ids,
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 10,
y: 10,
floating: false,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y;
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Players',
data: total_players
}, {
name: 'Bets',
data: total_bets
}]
});
}
else
{
if (newChartsPoints.length > 0)
{
$.each(newChartsPoints, function(index, value)
{
// retreive data
var temp_round_id = value[0];
var temp_total_players = value[1][0];
var temp_total_bets = value[1][1];
// add points
var series = charts[0].series;
series[0].addPoint([temp_round_id, temp_total_players], false);
series[1].addPoint([temp_round_id, temp_total_bets], false);
// add categories
categories = charts[0].xAxis[0].categories;
categories.push(temp_round_id);
charts[0].xAxis[0].setCategories(categories, false);
charts[0].redraw();
});
}
}

Categories

Resources