14

I was very surprised that I found almost no information about this topic.

I have a ChartJS pie chart that I want to drill down into after clicking a slice of the pie.

How would you do that?

Thank you

AlonBA
  • 444
  • 1
  • 4
  • 18
  • I think it's important for this question to be here, because the other answer is not labeled as "Drill down" so most people wouldn't find it. This question can reference them in the right direction. In addition - i inserted the jsfiddle code into the answer, and made some impovements to it. – AlonBA Aug 02 '18 at 08:24
  • 2
    I think this is a valid question and shouldn't be closed, because even if you capture events you can't achieve drilldown funcionality straight away. I had to destroy the previous chart and reload with new data on same html element. – Muhammad Ashhar Hasan Dec 19 '19 at 09:14
  • 2
    Um why was this closed?? It is definitely on topic. – trpt4him Jun 26 '21 at 17:49

1 Answers1

9

I've solved my problem using this awesome answer:

Click events on Pie Charts in Chart.js

The code:

    $(document).ready(function() {
      var canvas = document.getElementById("myChart");
      var ctx = canvas.getContext("2d");
      var myNewChart = new Chart(ctx, {
         type: 'pie',
         data: data
      });

      canvas.onclick = function(evt) {
      var activePoints = myNewChart.getElementsAtEvent(evt);
      if (activePoints[0]) {
         var chartData = activePoints[0]['_chart'].config.data;
         var idx = activePoints[0]['_index'];

         var label = chartData.labels[idx];
         var value = chartData.datasets[0].data[idx];
         var color = chartData.datasets[0].backgroundColor[idx]; //Or any other data you wish to take from the clicked slice

         alert(label + ' ' + value + ' ' + color); //Or any other function you want to execute. I sent the data to the server, and used the response i got from the server to create a new chart in a Bootstrap modal.
       }
     };
  });

That works perfectly. Just instead of alerting the information, i send it to the server using AJAX, and displaying a new chart in a bootstrap modal.

AlonBA
  • 444
  • 1
  • 4
  • 18
  • 2
    You can do this into the same html without modal. Just call .clear() and .destroy() methods on chart variable and then reload the same chart with different values. – Muhammad Ashhar Hasan Dec 19 '19 at 09:19