3

Hello All instead of simple Circles, i want to add pie charts in my Pack layout.

Lets Suppose this is my pie chart data and pie layout

var data=[2,3,4,5]

var arc = d3.svg.arc() .outerRadius(50) .innerRadius(0);

var pie = d3.layout.pie() .sort(null)

.value(function(d) { return d; });

And this is how the packlayout draws the circle

  var circle = svg.selectAll("circle")
  .data(nodes1)
  .enter().append("circle")
  .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; })
  .style("fill", function(d) { return d.children ? color(d.depth) : null; })
  .on("click", function(d) { if (focus !== d) zoom(d), d3.event.stopPropagation(); }); 

Can anyone please explain me how instead of appending circles in pack layout i could rather append paths and make pie charts out of it?![enter image description here][1]

VividD
  • 10,456
  • 6
  • 64
  • 111
Aditeya Pandey
  • 661
  • 2
  • 6
  • 13

1 Answers1

6

Instead of using the pack layout results directly, you can use the r value output from the pack layout to define the outerRadius of your arc generator. Then, instead of appending svg circle elements to the chart, you can append svg g elements, and append each of the arcs inside that:

Full example: http://bl.ocks.org/jsl6906/4a1b818b64847fb05d56 Pack layout with pie charts

Relevant code:

var bubble = d3.layout.pack()
      .value(function(d) { return d3.sum(d[1]); })
      .sort(null)
      .size([diameter, diameter])
      .padding(1.5),
    arc = d3.svg.arc().innerRadius(0),
    pie = d3.layout.pie();

var svg = d3.select("body").append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
    .attr("class", "bubble");

var nodes = svg.selectAll("g.node")
    .data(bubble.nodes({children: data}).filter(function(d) { return !d.children; }));
nodes.enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

var arcGs = nodes.selectAll("g.arc")
    .data(function(d) {
      return pie(d[1]).map(function(m) { m.r = d.r; return m; });
    });
var arcEnter = arcGs.enter().append("g").attr("class", "arc");

arcEnter.append("path")
    .attr("d", function(d) {
      arc.outerRadius(d.r);
      return arc(d);
    })
    .style("fill", function(d, i) { return color(i); });
Josh
  • 5,460
  • 31
  • 38
  • Thank you josh! It worked, though i tried it other way round by moving the pie chart to the position of respective pack layout bubbles. – Aditeya Pandey Nov 11 '14 at 04:29
  • 1
    Updated to v4 here: https://bl.ocks.org/jsl6906/6560687444d2e1421e4d24360c27728a/5d42f667eff12db4e95708ffe8169fa69d5a08f9 – Josh Jan 16 '18 at 21:57