title: d3.js force layout auto zoom/scale after loading
body: <p>I'm using <a href="http://flowingdata.com/2012/08/02/how-to-make-an-interactive-network-visualization/" rel="nofollow noreferrer">this nice force layout</a> from Flowingdata.com to create a network diagram.</p>
  <p><img src="https://i.stack.imgur.com/5jiXv.png" alt="enter image description here" /></p>
  <p><img src="https://i.stack.imgur.com/Ed8Bi.png" alt="enter image description here" /></p>
  <p><img src="https://i.stack.imgur.com/qupSX.png" alt="enter image description here" /></p>
  <p>My diagram currently shows between 5 and 750 nodes with their relations. It works great with some custom changes to fit my needs. However one thing I can't get to work. I have a <code>viewBox</code> with <code>preserveAspectRatio</code> to auto-fit the container it is in. But depending on the number of nodes there are always some nodes around the edges (mainly top and bottom) that get cut off. And if there are very few nodes, it shows them in the middle with huge empty space around it (it's a big container it's in).</p>
  <p>Is there any way to auto-zoom or scale the layout to auto-fit? So that a big layout gets somewhat zoomed out and a small layout zoomed in. I have a zoom event setup so scrolling and panning work like a charm. But can it automatically do that to fit the contents?</p>
  <p>The d3.js startup code:</p>
  <pre><code>vis = d3.select(selection)
    .append(&quot;svg&quot;)
    .attr(&quot;viewBox&quot;, &quot;0 0 &quot; + width + &quot; &quot; + height )
    .attr(&quot;preserveAspectRatio&quot;, &quot;xMidYMid meet&quot;)
    .attr(&quot;pointer-events&quot;, &quot;all&quot;)
    .call(d3.behavior.zoom().scaleExtent([.1, 3])
      .on(&quot;zoom&quot;, redraw)).append('g');
  </code></pre>