Malolillo
Malolillo

Reputation: 13

D3 tree level selector

Could I add a level selector for these trees created with d3.js?

http://bl.ocks.org/mbostock/2966094 or bl.ocks.org/mbostock/4339083

Add a label on each level to get the level position or expand it.

Added a example picture.

Example

Upvotes: 1

Views: 1263

Answers (1)

tarulen
tarulen

Reputation: 2100

Taking the example here: http://bl.ocks.org/mbostock/4339083

I would start by nesting the nodes by level:

var nodesByLevel = d3.nest().key(function (d) {return d.depth}).entries(nodes);

To add your boxes, do something like:

svg.selectAll(".levelBox")
  .data(nodesByLevel)
  .enter()            // one box per level
  .append("text")
  .attr("class","levelBox")
  .attr("x", function (d) {return d.values[0].x}) //take the x of the first node in this layer
  .text(function(d) {return d.key}) //the key from the nesting, i.e. the depth      
  .onclick(levelExpand);  // click handler

The above is just a skeleton, that should go into the update function (you need to take care of the exit() and update() selections after adding the data, and any additional drawing features).

In levelExpand, you have access to the list of nodes for the box that is clicked (in d.values). You can then go through the list, expand them, and then update the drawing

function levelExpand(d) {
    d.values.forEach(function (n) {n.children = n._children;}); //expand all nodes internally
   update(root); //show the update
}

Upvotes: 1

Related Questions