[Chartjs]-How to sort tooltip value in Chart.js

3πŸ‘

βœ…

It seems to work when I replace tooltips by tooltip. The show stopper may be console.log(a) that tries to log a really big object, try to log a.raw instead.

var bCtx = document.getElementById('bChart');

var data = {
  labels: ['a', 'b', 'c'],
  datasets: [{
    label: 'test',
    data: [10, 19, 5]
  }, {
    label: 'test',
    data: [9, 17, 3]
  }, {
    label: 'test',
    data: [15, 18, 4]
  }]
};

var bChart = new Chart(bCtx, {
  type: 'line',
  data: data,
  options: {
    responsive: true,
    interaction: {
      mode: 'index',
      intersect: false,
    },
    stacked: false,
    plugins: {
      tooltip: {
        itemSort: function(a, b) {
          return b.raw - a.raw;
        }
      },
      title: {
        display: false,
      }
    },
    scales: {
      y: {
        type: 'linear',
        display: true,
        position: 'left',
      },
      y1: {
        type: 'linear',
        display: true,
        position: 'right',
        grid: {
          drawOnChartArea: false, 
        }
      }
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.min.js"></script>
<canvas id="bChart"></canvas>

Leave a comment