Search code examples
highcharts

Customizing default y-axis label in Highcharts


I want to prefix a $ to the default y-axis label. My bar chart is using values in the millions so the chart is returning value-MM (80MM, 30MM). What I would like to do is format the y-axis like $-value-MM ($80MMm $30MM). I have tried the code below and can't get it to work?

yAxis: [{ // Primary yAxis
    labels: {
        formatter: function () {
            return '$' + this.value;
        }
    },
    title: {
        text: 'Revenue',

Solution

  • One rather elaborate way to achieve this is to re-use the code Highcharts uses in their internal defaultLabelFormatter for axis that are numeric, and use it in the axis formatter.

    An example of this, with your added prefix (JSFiddle):

    yAxis: {
        labels: {
            formatter: function() {
                var numericSymbols = Highcharts.getOptions().lang.numericSymbols;
                var i = numericSymbols && numericSymbols.length;
                var numericSymbolDetector = this.axis.isLog ? this.value : this.axis.tickInterval;
                var UNDEFINED, ret, multi;
    
                while (i-- && ret === UNDEFINED) {
                    multi = Math.pow(1000, i + 1);
                    if (numericSymbolDetector >= multi && (this.value * 10) % multi === 0 && numericSymbols[i] !== null) {
                        ret = Highcharts.numberFormat(this.value / multi, -1) + numericSymbols[i];
                    }
                }
    
                if (ret === UNDEFINED) {
                    if (Math.abs(this.value) >= 10000) { 
                        ret = Highcharts.numberFormat(this.value, -1);
    
                    } else {
                        ret = Highcharts.numberFormat(this.value, -1, UNDEFINED, '');
                    }
                }
    
                return "$"+ret; // Adding the prefix
            }
        },
    }
    

    A experimental short form of this would be to call the defaultLabelFormatter with the essential parts of the context it requires. An example of this (JSFiddle):

    yAxis: {
        labels: {
            formatter: function() {
                return "$" + this.axis.defaultLabelFormatter.call(this);
            }
        },
    }
    

    As the context is incomplete it wouldn't work as expected if your axis was datetime or categories or perhaps logarithmical, but should work for numeric axis. For the full picture I suggest looking at the full defaultLabelFormatter implementation.