d3 Tree - How to auto adjust node spacing when zooming

Viewed 250

I have a d3 tree with zoom and pan functionality. The tree can have a great number of child nodes for any parent. This can result in vertically squashed up nodes.

enter image description here

I would like the nodes to automatically adjust their spacing when zooming out, especially the vertical spacing.

The appending d3 svg and the zoom part of the d3 code:

var svg = d3.select("#tree_container")
.append("svg")
  .attr("width", width + margin.right + margin.left)
  .attr("height", height + margin.top + margin.bottom)
  .call( d3.behavior.zoom().on( "zoom", function () {
                    svg.attr( "transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")" )
                } ) )
  .append("g");

Fiddle

1 Answers

Would it be enough to set the node sizes? Then d3 will automatically adjust positions of the nodes.

var radius = 10;

var tree = d3.layout.tree()
  .size([height, width])
  .nodeSize([radius*2+3]);

...

function update(source) {

  ...

  nodeUpdate.select("circle")
    .attr("r", radius)

As Fiddle

Related