Mike S
Mike S

Reputation: 1613

d3 Circle Packing - Printing labels with multiple lines

I'm brand new to d3 (and JavaScript in general), and I'm trying to figure out how to alter this example so that each circle has its corresponding size field printed below the name. I tried just altering the JSON so the name fields were something like "MergeEdge\n743", but this did not work (it seems to just ignore the newline and print all on one line). Any tips?

Upvotes: 1

Views: 390

Answers (1)

Pierre Capo
Pierre Capo

Reputation: 1053

A little tip, usually with d3 you prefer to have separate code for different objectives. It makes it easier to maintain and overall make it more understandable when you read your file. In your case, we need to add a new text field, with coordinates which place the text below the current one. So we need to add :

node.filter(function(d) { return !d.children; }).append("text")
  .attr("dy", "1.2em")
  .text(function(d) { return Math.round(d.r).toString(); });

So the entire javaScript code will be :

var svg = d3.select("svg"),
    diameter = +svg.attr("width"),
    g = svg.append("g").attr("transform", "translate(2,2)"),
    format = d3.format(",d");

var pack = d3.pack()
    .size([diameter - 4, diameter - 4]);

d3.json("flare.json", function(error, root) {
  if (error) throw error;

  root = d3.hierarchy(root)
      .sum(function(d) { return d.size; })
      .sort(function(a, b) { return b.value - a.value; });

  var node = g.selectAll(".node")
    .data(pack(root).descendants())
    .enter().append("g")
      .attr("class", function(d) { return d.children ? "node" : "leaf node"; })
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

  node.append("title")
      .text(function(d) { return d.data.name + "\n" + format(d.value); });

  node.append("circle")
      .attr("r", function(d) { return d.r; });

  node.filter(function(d) { return !d.children; }).append("text")
      .attr("dy", "0.3em")
      .text(function(d) { return d.data.name.substring(0, d.r / 3); });

  node.filter(function(d) { return !d.children; }).append("text")
      .attr("dy", "1.2em")
      .text(function(d) { return Math.round(d.r).toString(); });
});

Upvotes: 1

Related Questions