[Chartjs]-ChartJS – Adding legend title into tooltip title

5👍

You can define a tooltips title callback as follows:

tooltips: {
  callbacks: {
    title: (tooltipItems, data) => tooltipItems[0].xLabel + ' ' +  data.datasets[tooltipItems[0].datasetIndex].label,
    ...
  }

Please take a look at your amended code and see how it works.

var barGraph = new Chart('chart', {
  type: 'bar',
  data: {
    labels: ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Jui', 'Jui', 'Aou', 'Sep', 'Oct', 'Nov', 'Dec'],
    datasets: [{
        label: '2019',
        data: [3, 4, 5, 2, 3, 2, 3, 4, 1, 2, 4, 5],
        backgroundColor: 'blue'
      },
      {
        label: '2020',
        data: [3, 4, 1, 2, 4, 5, 3, 4, 5, 2, 3, 2],
        backgroundColor: 'green'
      }
    ]
  },
  options: {
    responsive: true,
    legend: {
      position: 'right',
    },
    title: {
      display: true,
      text: 'Consommation électrique'
    },
    tooltips: {
      enabled: true,
      mode: 'single',
      callbacks: {
        title: (tooltipItems, data) => tooltipItems[0].xLabel + ' ' +  data.datasets[tooltipItems[0].datasetIndex].label,
        label: tooltipItems => tooltipItems.yLabel + ' kW'
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true, 
          callback: value => value + ' kW'
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" height="100"></canvas>

Leave a comment