1

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 is not working. I have also tried doing this here:

 var pieChartHome = new Chart(
    "myChart",
    {
  type: 'doughnut',
  data: {
    labels: ['One', 'Two', 'Three'],
    datasets: [{
      data: [4, 5, 3],
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(54, 162, 235, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(54, 162, 235)'],
      hoverBackgroundColor: ['rgba(255, 99, 132, 0.4)', 'rgba(255, 159, 64, 0.4)', 'rgba(54, 162, 235, 0.4)'],
      borderWidth: 1,
      hoverBorderWidth: 3
    }]
  },
    options: {
    responsive:false,
      plugins: {
      
        legend: {
        position:'right',
              onHover: (evt, legendItem,legend) => {
        const index = pieChartHome.data.labels.indexOf(legendItem.text);
        const rect = pieChartHome.canvas.getBoundingClientRect();
        
        const point = pieChartHome.getDatasetMeta(0).data[index].getCenterPoint();
        const e = new MouseEvent('mousemove', {
          clientX: rect.left + point.x,
          clientY: rect.top + point.y
        });
        pieChartHome.canvas.dispatchEvent(e);
      },
        }
        
      }
    },
  }
  );
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <div>
    <canvas id="myChart"></canvas>

  </div>

But this shows me flickering data and not something like this: Chart.js - show tooltip when hovering on legend

rama
  • 15
  • 6

1 Answers1

0

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');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69