首页 文章

格式化Highcharts y轴标签

提问于
浏览
23

我正在使用Highcharts生成一个显示货币值的折线图 . 默认情况下,y轴标签使用公制前缀作为缩写,例如显示3k而不是3000

我想在这些标签前加一个货币符号,例如:显示$ 3k而不是3k . 但是,只要我添加货币符号,就不再使用指标前缀 . 我尝试了以下内容

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

并尝试过

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

但在这两种情况下都会显示$ 3000而不是$ 3k . 是否可以添加货币符号而不会丢失指标前缀?

这是一个说明问题的演示(JSFiddle here

$(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>

2 回答

  • 2

    您可以从格式化程序函数调用原始格式化程序:

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

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

  • 38

    我查看了HighCharts源代码,发现如果你传递 formatformatter 它将不会添加数字符号 . 它在 else if 语句中,即formatOption xor numericSymbol . 所以你需要添加一个格式化程序并自己完成逻辑 .

    这是他们代码的略微修改的复制粘贴:

    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/

相关问题