salty_coffee
salty_coffee

Reputation: 631

Explode segment of donut/pie chart segment

Im trying to learn d3.

I was hoping I could get some guidance on how to 'explode' a pieSegment with a mouseover event in d3 (hover). Iv been trying to figure out how to explode a segment using the .on() method in d3 but I have had no luck.

edit: to clarify, I am trying to move a pieSegment further away from the centre of the pie, while leaving the rest stationary.

index.html

<!DOCTYPE html>
<html>
<head>
  <link href="style.css" rel="stylesheet">
  <script src="http://d3js.org/d3.v3.min.js"></script>
</head>

<body>
<script>
    var data = [21, 32, 35, 64, 83];
    var pieSegments = d3.layout.pie()(data);

    var canvas = d3.select("body")
      .append('svg')  
      .attr("height", 500)
      .attr("width",500);

    var generator = d3.svg.arc()
    .innerRadius(70)
    .outerRadius(100)
    .startAngle(function(d){return d.startAngle;})
    .endAngle(function(d){return d.endAngle});

    var colors = d3.scale.category10();

    canvas.selectAll('path').data(pieSegments).enter().append('path')
        .attr("d", generator)
        .attr("fill", function(d,i){return colors(i);})
        .attr("stroke", "white")
        .attr("stroke-width", 6)
        .attr("transform", "translate(100,100)");
</script>
</body>
</html>

Upvotes: 2

Views: 872

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

An easy solution is creating another arc generator...

var generator2 = d3.svg.arc()
    .innerRadius(80)
    .outerRadius(110);

... and using it on the mouseover:

.on("mouseover", function(){
    d3.select(this).attr("d", generator2)
})

Here is your code with those changes:

var data = [21, 32, 35, 64, 83];
var pieSegments = d3.layout.pie()(data);

var canvas = d3.select("body")
  .append('svg')
  .attr("height", 300)
  .attr("width", 300);

var generator = d3.svg.arc()
  .innerRadius(70)
  .outerRadius(100)
  .startAngle(function(d) {
    return d.startAngle;
  })
  .endAngle(function(d) {
    return d.endAngle
  });

var generator2 = d3.svg.arc()
  .innerRadius(80)
  .outerRadius(110);

var colors = d3.scale.category10();

canvas.selectAll('path').data(pieSegments).enter().append('path')
  .attr("d", generator)
  .attr("fill", function(d, i) {
    return colors(i);
  })
  .attr("stroke", "white")
  .attr("stroke-width", 6)
  .attr("transform", "translate(150,150)")
  .on("mouseover", function() {
    d3.select(this).attr("d", generator2)
  })
  .on("mouseout", function() {
    d3.select(this).attr("d", generator)
  })
<script src="https://d3js.org/d3.v3.min.js"></script>

PS: Don't call a SVG selection as canvas... it's confusing. When we see var canvas, we associate it to a HTML5 canvas. Use var svg instead.

Upvotes: 2

Related Questions