[Chartjs]-How can I create custom tooltips for each data point in a graph?

1👍

Your tooltips.callbacks should look as follows:

tooltips: {
  callbacks: {
    title: (tooltipItems, data) => data.labels[tooltipItems[0].index],
    label: (tooltipItems, data) => data.datasets[tooltipItems.datasetIndex].label + ' ' + data.datasets[tooltipItems.datasetIndex].data[tooltipItems.index],
    footer: (tooltipItems, data) => ['', 'Description:'].concat(data.datasets[tooltipItems[0].datasetIndex].info)
  }
}

Please have a look at your amended code below:

var colors = ['#007bff', '#28a745', '#333333', '#c3e6cb', '#dc3545', '#6c757d'];

var ctx = document.getElementById('chBar');
new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Proportion of Coded Projects'],
    datasets: [{
        label: 'Coded Projects',
        data: [70],
        backgroundColor: '#D6E9C6',
        info: [
          ['This refers to projects that have not'],
          ['been qualitatively coded using the TDF.']
        ]
      },
      {
        label: 'Remaining Projects',
        data: [170],
        backgroundColor: colors.slice(0, 1),
        info: [
          ['This refers to total number'],
          ['of projects left to code.']
        ]
      }
    ]
  },
  options: {
    tooltips: {
      callbacks: {
        title: (tooltipItems, data) => data.labels[tooltipItems[0].index],
        label: (tooltipItems, data) => data.datasets[tooltipItems.datasetIndex].label + ' ' + data.datasets[tooltipItems.datasetIndex].data[tooltipItems.index],
        footer: (tooltipItems, data) => ['', 'Description:'].concat(data.datasets[tooltipItems[0].datasetIndex].info)
      }
    },
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
});
canvas {
  max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chBar"></canvas>

Leave a comment