Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NVD3 Create click event for individual slice of a pie chart

I am using NVD3 to create a pie chart. code to generate pie chart:

nv.addGraph(function() {
        var chart = nv.models.pieChart().x(function(d) { return d.label }).y(function(d) { return d.value }).showLabels(true);
        d3.select("#chart svg").datum(exampleData()).transition().duration(350).call(chart);
        return chart;

        function exampleData() {
            return vm.chartData.userData;   
        }
    });

Now I have two slices in the pie chart as shown.

enter image description here

I have used the following approach 1)use js on method

var svg = d3.selectAll("#chart svg");
svg.select(".nv-pie").selectAll(".nv-slice")
.on('mouseover',function(d){
    console.log(d);
});

But no click event is happening.

Please correct me where I am wrong.

like image 213
rahul Avatar asked Feb 08 '23 07:02

rahul


1 Answers

Use this:

chart.pie.dispatch.on("elementClick", function(e) {
    console.log(e);
});

Demo

var chartElement = d3.select("#chart svg");
var chart;

nv.addGraph(function() {
  chart = nv.models.pieChart()
    .x(function(d) {
      return d.label
    })
    .y(function(d) {
      return d.value
    })
    .showLabels(true);

  var chartData = [{
    label: "Foo",
    value: 67
  }, {
    label: "Bar",
    value: 33
  }];

  chartElement
    .datum(chartData)
    .call(chart);

  chart.pie.dispatch.on("elementClick", function(e) {
    alert("You've clicked " + e.data.label);
  });

  return chart;
});
#chart {
  height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.2/nv.d3.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.2/nv.d3.min.css" rel="stylesheet" />
<div id="chart">
  <svg></svg>
</div>
like image 105
Luc Avatar answered Feb 09 '23 19:02

Luc