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.
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.
Use this:
chart.pie.dispatch.on("elementClick", function(e) {
console.log(e);
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With