简体   繁体   中英

How to set a global chart.js tooltip label callback

I would like to globally set the number formatting for different Chart.js types, including: bar, line, horizontalBar, radar.

The following works for everything except horizontalBar:

Chart.defaults.global.tooltips.callbacks.label =  function(tooltipItem, data, index) {
  var label = data.datasets[tooltipItem.datasetIndex].label || '';
  if (label) {
      label += ': ';
      }
  label += tooltipItem.yLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
  return label;}

This fails for horizontalBar, because the axis changes from y to x. Changing .yLabel. to .xLabel. in the above thus works for horizontalBar, however, fails for the others.

I tried setting horizontalBar defaults separately with

Chart.defaults.horizontalBar.tooltips.callbacks.label =  function(tooltipItem, data, index) {
  var label = data.datasets[tooltipItem.datasetIndex].label || '';
  if (label) {
      label += ': ';
      }
  label += tooltipItem.xLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
  return label;}

which gives me a "Uncaught TypeError: tooltipItem.yLabel.toFixed is not a function"

I could also not figure out how to get the chart type within function(tooltipItem, data, index) {} otherwise one could set the y/xlabel conditional on the type.

There are 2 ways, the first one is by checking if the value is a number, this way you can get the xAxes value if its a horizontal bar. Fallback in else for if both axis are text values

Chart.defaults.global.tooltips.callbacks.label = function(tooltipItem, data, index) {
    var label = data.datasets[tooltipItem.datasetIndex].label || '';
    if (label) {
        label += ': ';
    }
    if (typeof tooltipItem.yLabel === 'number') {
        label += tooltipItem.yLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    } else if (typeof tooltipItem.xLabel === 'number') {
        label += tooltipItem.xLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    } else {
        label += tooltipItem.value
    }
    return label;
}

You can also check if the value from the tooltip is a number and use that instead of the labels, this will require a typecast so it will be more resource intensive:

Chart.defaults.global.tooltips.callbacks.label = function(tooltipItem, data, index) {
    var label = data.datasets[tooltipItem.datasetIndex].label || '';
    if (label) {
        label += ': ';
    }
    if (Number(tooltipItem.value)) {
        label += Number(tooltipItem.value).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    } else {
        label += tooltipItem.value
    }
    return label;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM