Customizing default y-axis label in Highcharts

℡╲_俬逩灬. 提交于 2019-12-12 16:34:57

问题


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',

回答1:


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({
                axis: this.axis,
                value: this.value
            });
        }
    },
}

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.




回答2:


If I understand the question correctly, your data already has 'MM' suffix and you want to add the prefix '$'.

Try,

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


来源:https://stackoverflow.com/questions/36119462/customizing-default-y-axis-label-in-highcharts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!