Chartjs-Show all data when a tooltip is triggered in Chart.js

2👍

You can try to use the mode: ‘dataset’ in tooltip config:

let ctx = document.getElementById('myChart').getContext('2d')
let myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['January', 'February', 'March', 'April'],
    datasets: [{
      label: 'Data',
      data: [12, 19, 3, 5],
      borderColor: 'blue'
    }]
  },
  options: {
    plugins: {
      tooltip: {
        mode: 'dataset',
        callbacks: {
          label: function (tooltipItem) {
            return [tooltipItem.label, tooltipItem.raw].toString();
          }
        }
      }
    }
  }
});
.as-console-row-code {
  white-space: initial !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.0/chart.min.js"></script>
<canvas id="myChart"></canvas>

1👍

In the label callback function of the tooltip plugin, you can access the chart object and get the labels and data for each tooltip item using the getDatasetMeta and data methods.

let ctx = document.getElementById('myChart').getContext('2d');
let myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['January', 'February', 'March', 'April'],
    datasets: [{
      label: 'Data',
      data: [12, 19, 3, 5],
      borderColor: 'blue'
    }]
  },
  options: {
    plugins: {
      tooltip: {
        mode: 'nearest',
        callbacks: {
          label: function (tooltipItem, chart) {
            let datasetIndex = tooltipItem.datasetIndex;
            let dataIndex = tooltipItem.index;
            let label = chart.data.labels[dataIndex];
            let value = chart.data.datasets[datasetIndex].data[dataIndex];
            console.log([[label, value]]);
            return value;
          }
        }
      }
    }
  }
});
.as-console-row-code {
  white-space: initial !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.0/chart.min.js"></script>
<canvas id="myChart"></canvas>

Leave a comment