【问题标题】:Format Highcharts y-axis labels格式化 Highcharts y 轴标签
【发布时间】:2017-12-16 01:44:25
【问题描述】:

我正在使用 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>

【问题讨论】:

    标签: javascript highcharts


    【解决方案1】:

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

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

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

    【讨论】:

    【解决方案2】:

    我查看了 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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多