How to Format Highcharts dataLabels Decimal Points - highcharts

Can you please take a look at this example and let me know how I can format the dataLabels to be display only with two decimal numbers?
Here is the numver formats which I have in the series
series: [{
name: 'Tokyo',
data: [7.554555, 6.34345559, 9.5555, 14.5555, 18.4333433, 21.5555, 25.2, 26.5333333, 23.33333, 18.23243543, 13.776565669, 9.65454656]
}, {
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
and I would like to present them like 7.55 , 6.34, 9.55 . Thanks

You need to combine the dataLabels formatter and Highcharts.numberFormat:
...
dataLabels: {
enabled: true,
formatter: function () {
return Highcharts.numberFormat(this.y,2);
}
}
...
See jsFiddle

I would simply add a the format option to data labels as follows:
dataLabels: {
enabled: true,
format: '{point.y:,.2f}'
}
It's the simple way of doing it without having to define a function using formatter.
extra:
The comma after the colon makes sure that a number like 1450.33333 displays as 1,450.33 which is nice also.

In case someone wants to go "further", I'm showing data that can be 10^1 to 10^9 so I'm converting them and showing the unit afterwards.
Remember, Highcarts deals only with integers so if you want to add units (and not in the YAxis because of multiple units) you can give it in the source data but you have to format them afterwards:
column: {
dataLabels: {
enabled: true,
formatter: function () {
// Display only values greater than 0.
// In other words, the 0 will never be displayed.
if (this.y > 0) {
if (this.y >= Math.pow(10, 9))
{
return Highcharts.numberFormat(this.y /Math.pow(10, 9) , 1) + " mias";
}
else if (this.y >= Math.pow(10, 6))
{
return Highcharts.numberFormat(this.y /Math.pow(10, 6) , 1) + " mios";
}
else
{
return Highcharts.numberFormat(this.y, 0);
}
}
},
mias : stands for "milliards" (french translation of billiards)
mios : stands for "millions" (french translation of millions)

I noticed in the comments you wanted to not display trailing zeroes.
This was the simplest solution I was able to muster:
...
dataLabels: {
enabled: true,
formatter: function () {
return parseFloat(this.y.toFixed(2)).toLocaleString();
}
}
...
If you don't want the number to end up with a comma-separator (depending on locale) remove the .toLocaleString().
Sidenote: Unfortunately using format (instead of formatter and a js func like we do above) is limited to a subset of float formatting conventions from the C library function sprintf, as indicated here on highcharts website. That library has the code g that would automatically do this for us but unfortunately it is not implemented in Highcharts :(, i.e. format: '{point.y:,.2g}' does not work.

Related

how to set character limit to 4-5 in axis labels in highcharts in angular 7

I'm using column, I need to reduce x axis characters to max 4-5 character which is dynamically coming from database.
xAxis: {
categories: labesldata,
crosshair: true
}
You can use the formatter callback function and modify the default string:
xAxis: {
...,
labels: {
formatter: function() {
return this.value.slice(0, 5);
}
}
}
Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4931/
API Reference: https://api.highcharts.com/highcharts/xAxis.labels.formatter

Data labling in highcharts

Should be easy, I have negative values in a Highcharts bar chart that when I make the format ${y} the value comes out as $-157, what is the correct syntax to make the label -$157?
Thanks,
CM
I am unsure if there is a built-in option in Highcharts to do this for currencies, but a way you could achieve this is by using the formatter callback like this:
dataLabels: {
enabled: true,
formatter: function() {
return (this.y >= 0 ? '' : '-') + '$' + Math.abs(this.y)
}
}
Working JSFiddle example: http://jsfiddle.net/ewolden/4o7k210s/

Highcharts - Stack Graph Display Average of all values

I am using highcharts for statistical data displaying. I want to display , on the stack label , the average of all the values .
Below is what i am doing but i cant seem to get it right :
yAxis: {
min: 0,
title: {
text: 'Task'
},
stackLabels: {
style: {
color: 'black'
},
enabled: true,
formatter: function() {
return (this.axis.series[1].yData[this.x]).toPrecision(2) + '%';
}
}
},
The above only takes the last value on the stack and shows the percentage. For instance , if the last value is 50 , the above displays 50% as the stack value . I want to take an average of all the values. Any help would be appreciated.
If you want to show any stack's percentage mean if your stacked column has two stack A-5 and B-10 , then the % of B in column is 66% and % of A is 33%. If you want to show that use following in formatter function ( refer This Fiddle Link)
formatter: function() {
return (this.axis.series[1].yData[this.x] / this.total * 100).toPrecision(2) + '%';
}
Updating as per OP 's comment Refer Working fiddle here
Use following code : Make your data in a variable and calculate the sum
var seriesData = [{
name: 'Incomplete',
data: [1, 3, 4, 7, 20]
}, {
name: 'Complete',
data: [3, 4, 4, 2, 5]
}];
var total = 0;
$.each(seriesData,function(item){
$.each(seriesData[item].data,function() {
total += this;
});
});
And then use following in stacklabel formatter :
formatter: function() {
return ( this.total/ total * 100).toPrecision(2) + '%';
}
series:seriesData
hope it helps :)
This doesn't seem to be as easy as it should be.
I would accomplish this by pre-processing the data to generate an array of averages, and then referencing that array from the stackLabels formatter function.
Example, build the averages (assumes array 'data' with sub array for each series data values):
var sum = 0;
var averages = [];
var dataLen = data.length;
$.each(data[0], function(x, point) {
sum = 0;
for(var i = 0; i < dataLen; i++) {
sum += data[i][x];
}
averages.push(sum/dataLen);
})
And then in the formatter:
yAxis : {
stackLabels: {
enabled: true,
formatter: function() {
return Highcharts.numberFormat(averages[this.x],2);
}
}
}
Example:
http://jsfiddle.net/jlbriggs/vatdrecb/
If I could find a way to get a reliable count of the points in each stack, you could just use
return this.total/countOfPoints;
in the formatter without needing to build an array, but I can't seem to reliably get that count.

Highcharts for multiple plot lines each with a different color and show tooltip?

I have a flask app in which I am using Highcharts to plot data, and if the user enters a lot of inputs for which he needs a graph, I plot multiple plot lines on the graph with different colors. But after 8-10 plot lines the color repeat and hence its not useful coz its not distinguishable.
<script type="text/javascript">
$('document').ready(function(){
window.seriesOptions = [];
window.yAxisOptions = [],
window.seriesCounter = 0,
window.colors = Highcharts.getOptions().colors;
generate_graph( {{ coordinates| safe }} , {{ graph_name | safe }} );
});
</script>
/*
Generate graph function takes two input parameters i.e. Coordinates - which is an array of [x, y] points AND graph_name which is an array of the (service_name,server_name) pair and generates
seriesOptions and calls createChart function.
*/
function generate_graph(coordinates, graph_name){
$.each(graph_name, function(i, name) {
window.seriesOptions[i]= {
name : graph_name[i],
data : coordinates[i],
type : 'line'
};
seriesCounter++;
if (seriesCounter == graph_name.length) {
createChart();
}
});
$('#add-to-dashboard-button').show();
}
/*
createChart function generates the actual graphs and sets the different properties of the graph.
*/
function createChart(){
$('#chart').highcharts('StockChart', {
chart: {
zoomType: 'x'
},
rangeSelector: {
selected: 4
},
xAxis: {
type: 'datetime',
labels: {
formatter: function() {
return Highcharts.dateFormat('%a %d %b', this.value);
}
}
},
title : {
text : 'Graph'
},
legend: {
enabled: true,
layout: 'vertical',
labelFormat: '<span style="color:{color}">{name}</span> - <b> x : ({point.x:.2f}) , </b> y : ({point.y:.2f}) <br/>',
maxHeight: 100
},
series : seriesOptions
});
}
</script>
How to make sure that every time a plot is generated its in a different unique color and hence distinguishable.
Also The tooltip doesn`t appear even though the data for x axis is sorted?
If you don't specify any colours when creating a chart or adding a series, highcharts will pick one from it's default colours. There are a limited number of defaults.
However, you can tell highcharts about a new set of default colours, so you could give it more to chose from, up to the maxumum you want to support. This code sets 9 defaults, but you can add as many as you want, you just need to come up with some unique colours:
Highcharts.setOptions({
colors:[
'#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
Make this the first thing you call.

Highcharts: Show x-axis labels ony for years ending in zero (1950, 1960, 1970, ...)

I'm using Highcharts to create a column chart with data from 1947 to 2012. Is there a way to get the x-axis to display labels only when the years end with a zero?
So the chart would start with data for 1947, but the first x-axis labels would be "1950, 1960, 1970, ..." I.e., blank axis labels for 1947, 1948, 1949, 1951, 1952 ...
I see two options:
1.) specify your own ticks at the 10 year marks:
tickPositions: [Date.UTC(1950, 0, 1),Date.UTC(1960, 0, 1),Date.UTC(1970, 0, 1),...]
For this to work you'll also need to specify a custom formatter:
labels: {
formatter: function () {
return Highcharts.dateFormat('%Y', this.value);
}
}
2.) let Highcharts create the ticks and then 'discard' the ones that don't start a decade
labels: {
formatter: function () {
var strVal = Highcharts.dateFormat('%Y', this.value);
if (strVal.endsWith('0')){
return strVal;
} else {
return "";
}
}
}
Here's a fiddle demonstrating both approaches.

Resources