Search code examples
d3.jsclickabledonut-chart

Make donut chart clickable


Can anybody help me regarding how I can make my following donut chart Clickable? I am just creat a donut chart from some dummy data and want each portion of the donut to be clickable. I am quite new in D3 and finding it hard to incorporate the click function in the donut chart. I am finding it difficult to make each portion of the donut chart clickable in d3.js. Any help is appreciated. I have added my code snippet here.

function myFunction(width,height,margin,datax,dis,hg) {
    var radius = Math.min(width, height) / 2 - margin
    var svg = d3.select("#my_dataviz")
      .append("svg")
        .attr("width", width)
        .attr("height", hg)
      .append("g")
        .attr("transform", "translate(" + width / dis + "," + height / 2 + ")");
    var color = d3.scaleOrdinal()
      .domain(Object.keys(data))
      .range(d3.schemeDark2);
    var pie = d3.pie()
      .sort(null) 
    .value(function(d) {return d.value; })  
    var data_ready = pie(d3.entries(data))
    var arc = d3.arc()
      .innerRadius(radius * 0.5)       
    .outerRadius(radius * 0.8)
    svg
      .selectAll('allSlices')
      .data(data_ready)
      .enter()
      .append('path')
      .attr('d', arc)
      .attr('fill', function(d){ return(color(d.data.key)) })
      .attr("stroke", "white")
      .style("stroke-width", "2px")
    .style("opacity", 0.7)
    ;  }
    <script src="https://d3js.org/d3.v4.js"></script>
    <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>

Solution

  • You just need to select all path and bind event click on it

    svg.selectAll('path')
       .on('click', (d, i, n) => {
          console.log(d, i, n)
       })