1
votes

I'm using Chart.js 2.1.4 and I would like to sort tooltip items based on the tooltip item value (yAxis value). I would also like to add thousands separator to values.

The lines in following picture should be sorted based on the value:

Dataset tooltips

This adds separator for Scales: Chart.js 2.0 Formatting Y Axis with Currency and Thousands Separator

Using Documentation: http://www.chartjs.org/docs/#chart-configuration-tooltip-configuration and the Question above I have tried modifying the code for Tooltips value:

var chart_config = {
  type: 'line',
  data: {datasets: mydatasets},
  options: {
    tooltips: {
      mode: 'label',
      bodySpacing: 10,
      titleMarginBottom: 15,
      callbacks: {
        beforeLabel: function(tooltipItem, data) {
          var tooltipValue = tooltipItem.xLabel + ': ' + tooltipItem.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          console.log(tooltipValue);
          return tooltipValue;
        },
      },
    },
  }
};
var chartHolder = document.getElementById("chartHolder");
var chart = new Chart(chartHolder, chart_config);

The problem is it now returns only part of the tooltip items and there is error in console: TypeError: vm.labelColors[i] is undefined.

How should I format the function's return value to not have any errors and present the data as specified?

2

2 Answers

15
votes

You can use the itemSort callback option for tooltips, e.g.

tooltips: {
  itemSort: (a, b, data) => b.yLabel - a.yLabel
}
1
votes

You have this information in the Docs: ChartJS Tooltip Configuration Callbacks

You could do this:

var myChart;

myChart = {
  type: 'line',
  data: {
    datasets: mydatasets
  },
  options: {
    tooltips: {
      mode: 'label',
      callbacks: {
        title: function(tooltipItem) {
          return moment(tooltipItem[0].xLabel).format('ll');
        },
        label: function(tooltipItem, data) {
          return data.datasets[tooltipItem.datasetIndex].label + ": " + tooltipItem.yLabel;
        }
      }
    }
  }
};