Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Highcharts y-axis labels

I'm using Highcharts to generate a line chart that shows currency values. By default the y-axis labels use metric prefixes for abbreviation, e.g. 3k is displayed instead of 3000

I would like to prepend a currency symbol to these labels, e.g. display $3k instead of 3k. However as soon as I add the currency symbol, the metric prefixes are no longer used. I've tried the following

    yAxis: {         labels: {                             formatter: function () {                 return '$' + this.value;             }         }     } 

and also tried

    yAxis: {         labels: {             format: '${value}'         }     } 

But in both cases $3000 is displayed instead of $3k. Is it possible to add a currency symbol without losing the metric prefix?

Here's a demo (JSFiddle here) that illustrates the problem

$(function() {    $('#container').highcharts({        yAxis: {        // if you include the lines below, the metric prefixes disappear        /*        labels: {            format: '${value}'        }        */      },        series: [{        data: [15000, 20000, 30000]      }]      });  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>  <script src="https://code.highcharts.com/highcharts.js"></script>    <div id="container" style="height: 400px; width: 500px"></div>
like image 843
Dónal Avatar asked Sep 30 '14 18:09

Dónal


2 Answers

You can call the original formatter from your formatter function:

$(function () {     $('#container').highcharts({          yAxis: {                         labels: {                 formatter: function () {                     return '$' + this.axis.defaultLabelFormatter.call(this);                 }                         }         },          series: [{             data: [15000, 20000, 30000]         }]      }); }); 

http://jsfiddle.net/x6b0onkp/2/

like image 87
Barbara Laird Avatar answered Sep 26 '22 08:09

Barbara Laird


I looked in HighCharts source code and found out that if you pass a format or formatter it won't add numeric symbol. It is inside else if statement i.e. formatOption xor numericSymbol. So you need to add a formatter and do the logic yourself.

this is a slightly modified copy-paste of their code:

       formatter: function() {            var ret,                numericSymbols = ['k', 'M', 'G', 'T', 'P', 'E'],                i = numericSymbols.length;            if(this.value >=1000) {                while (i-- && ret === undefined) {                    multi = Math.pow(1000, i + 1);                    if (this.value >= multi && numericSymbols[i] !== null) {                       ret = (this.value / multi) + numericSymbols[i];                    }                }            }            return '$' + (ret ? ret : this.value);        } 

http://jsfiddle.net/x6b0onkp/1/

like image 24
Dmitry Avatar answered Sep 23 '22 08:09

Dmitry