Skip to content Skip to sidebar Skip to footer

Chart Js Show Data On Hovering Legend

I have a pie chart and I want to get the number/data of each section of pie chart when hovered upon. I have seen the implementation of this in version 2.9.x but in version 3.x it i

Solution 1:

You can set the tooltip via chart.js public methods itself:

var options = {
  type: 'doughnut',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    plugins: {
      legend: {
        position: 'left',
        onHover: (evt, item, legend) => {
          const chart = legend.chart;
          const tooltip = chart.tooltip;

          const chartArea = chart.chartArea;
          tooltip.setActiveElements([{
            datasetIndex: 0,
            index: item.index,
          }], {
            x: (chartArea.left + chartArea.right) / 2,
            y: (chartArea.top + chartArea.bottom) / 2,
          });


          chart.update();
        },
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
newChart(ctx, options);
<body><canvasid="chartJSContainer"width="600"height="400"></canvas><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script></body>

Post a Comment for "Chart Js Show Data On Hovering Legend"