[Chartjs]-Chart.js scatter chart – displaying label specific to point in tooltip

27👍

You can achieve this using the following tooltips label callback function …

tooltips: {
   callbacks: {
      label: function(tooltipItem, data) {
         var label = data.labels[tooltipItem.index];
         return label + ': (' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
      }
   }
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var ctx = document.getElementById('myChart').getContext('2d');
var scatterChart = new Chart(ctx, {
   type: 'scatter',
   data: {
      labels: ["Label 1", "Label 2", "Label 3"],
      datasets: [{
         label: 'Legend',
         data: [{
            x: -10,
            y: 0,
         }, {
            x: 0,
            y: 10
         }, {
            x: 10,
            y: 5
         }]
      }]
   },
   options: {
      tooltips: {
         callbacks: {
            label: function(tooltipItem, data) {
               var label = data.labels[tooltipItem.index];
               return label + ': (' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
            }
         }
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart" style="height:1000px"></canvas>

12👍

As of Chart.js version 3, callbacks are handled a little differently. Here is a working example with 3.2.0. Relevant docs: https://www.chartjs.org/docs/latest/configuration/tooltip.html#label-callback

ctx = document.getElementById("myChart").getContext("2d");

let data = {
    datasets: [{
        label: "Legend",
        labels: ["Label 1", "Label 2", "Label 3"],
        data: [{
            x: -10,
            y: 0,
        }, {
            x: 0,
            y: 10
        }, {
            x: 10,
            y: 5
        }],
        backgroundColor: "rgb(255, 99, 132)"
    }]
}

let options = {
    plugins: {
        tooltip: {
            callbacks: {
                label: function(ctx) {
                    // console.log(ctx);
                    let label = ctx.dataset.labels[ctx.dataIndex];
                    label += " (" + ctx.parsed.x + ", " + ctx.parsed.y + ")";
                    return label;
                }
            }
        }
    }
}

scatterChart = new Chart(ctx, {
    type: "scatter",
    data: data,
    options: options
});
<canvas id="myChart" height="500"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.min.js"></script>

5👍

For multiple labels GRUNT ‘s answer needs to be modified to use tooltipItem.datasetIndex instead of tooltipItem.index:

options: {
  tooltips: {
     callbacks: {
        label: function(tooltipItem, data) {
           var label = data.labels[tooltipItem.datasetIndex];
           return label + ': (' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
        }
     }
  } }

Leave a comment