Chart.js: how to order the tool tips in the graph

Viewed 27

I generate a graph where I have 3 groups of data:

  • bottom
  • middle
  • top

Each bar has the top values at the top of the bar, then the middle value and then the bottom value.

When Chart.js displays the tooltip, I have first the bottom value, then the middle and the the top. So, it is the opposite of the order in the bar.

enter image description here

To display the values I added this code

var stackedBarChartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    tooltips: {
        mode: 'label',
        callbacks: {
            label: function (tooltipItem, data) {
                return data.datasets[tooltipItem.datasetIndex].label + ": " + 
                       tooltipItem.yLabel;
            }
        }
    }
}

Is it possible to order the list of tool tips?

1 Answers

in the tooltip label callback, we can choose any index to display.
in your callback, you're displaying the index passed to the callback.

tooltipItem.datasetIndex

instead, let's display the reverse order...

data.datasets.length - 1 - tooltipItem.datasetIndex

but we will also have to add the callback for labelColor,
to display the correct color box for the specific label.

see following working snippet...

var chart_canvas = document.getElementById('myChart');
var stackedLine = new Chart(chart_canvas, {
  type: 'bar',
  data: {
    labels: ['A'],
    fill: true,
    datasets: [
      {
        label: 'Low',
        data: [67.8],
        backgroundColor: '#D6E9C6'
      },
      {
        label: 'Moderate',
        data: [20.7],
        backgroundColor: '#FAEBCC'
      },
      {
        label: 'High',
        data: [11.4],
        backgroundColor: '#EBCCD1'
      }
    ]
  },
  options: {
    responsive: true,
    maintainAspectRatio: false,
    tooltips: {
      mode: 'label',
      callbacks: {
        labelColor: function (tooltipItem, data) {
          return {backgroundColor: data.data.datasets[data.data.datasets.length - 1 - tooltipItem.datasetIndex].backgroundColor};
        },
        label: function (tooltipItem, data) {
          return data.datasets[data.datasets.length - 1 - tooltipItem.datasetIndex].label + ": " + data.datasets[data.datasets.length - 1 - tooltipItem.datasetIndex].data[tooltipItem.index];
        }
      }
    },
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

Related