设置高图表中工具提示数字的格式

Format tooltip numbers in Highcharts

本文关键字:格式 数字 工具提示 高图表 设置      更新时间:2023-09-26

我使用tooltip.pointFormat在工具提示中呈现其他数据。不幸的是,只有point.x的格式正确,带有一千位分隔符。

js小提琴

$(function () {
  Highcharts.setOptions({
    global: {
      useUTC: false,
    },
    lang: {
      decimalPoint: ',',
      thousandsSep: '.'
    }
  });
  $('#container').highcharts({
    xAxis: {
      type: 'datetime'
    },
    tooltip: {
      pointFormat: '{series.name}: <b>{point.y}</b><br/>' + 'Count: <b>{point.count}</b><br/>',
      shared: true
    },
    series: [{
      data: [{
        y: 20009.9,
        count: 20009.9
      }, {
        y: 10009.9,
        count: 20009.9
      }, {
        y: 40009.9,
        count: 20009.9
      }],
      pointStart: Date.UTC(2010, 0, 1),
      pointInterval: 3600 * 1000 // one hour
    }]
  });
});

在这里找到了答案。

数字使用浮点格式约定的子集进行格式设置 来自 C 库函数 sprintf。格式追加在内部 变量括号,用冒号分隔。例如:

  • 小数点后两位:"{point.y:.2f}"
  • 千位分隔符,无小数位:{point.y:,.0f}
  • 千位分隔符,小数点后一位:{point.y:,.1f}

因此,在括号内使用:,.1f将正确格式化数字。

tooltip: {
  pointFormat: '{series.name}: <b>{point.y}</b><br/>' + 'Count: <b>{point.count:,.1f}</b><br/>',
  shared: true
}

js小提琴

intFormat,使用工具提示格式化程序,然后使用Highcharts.numberFormat

tooltip: {
            formatter:function(){
                return this.point.series.name + ': <b>' + Highcharts.numberFormat(this.point.options.count,1,',','.') + '</b><br/>' + 'Count: <b>'+Highcharts.numberFormat(this.point.y,1,',','.')+'</b><br/>';
            }
        },

示例:http://jsfiddle.net/8rx1ehjk/4/

在我们的

例子中tooltipFormatter仅对y属性应用格式,我找到了几种方法不仅可以为y添加格式,

  1. 为每个工具提示和每个属性添加格式,如下所示point.count:,.f

    pointFormat: '{series.name}: <b>{point.count:,.f}</b><br/>' + 'Count: <b>{point.y}</b><br/>',
    
  2. 创建这样的小扩展

    (function (Highcharts) {
      var tooltipFormatter = Highcharts.Point.prototype.tooltipFormatter;
      Highcharts.Point.prototype.tooltipFormatter = function (pointFormat) {
        var keys = this.options && Object.keys(this.options),
            pointArrayMap = this.series.pointArrayMap,
            tooltip;
        if (keys.length) {
          this.series.pointArrayMap = keys;
        }     
        tooltip = tooltipFormatter.call(this, pointFormat);        
        this.series.pointArrayMap = pointArrayMap || ['y'];
        return tooltip;
      }
    }(Highcharts));
    

Example