I have been experimenting with D3’s cluster function using
http://bl.ocks.org/mbostock/4063570
as a guide.
If I copy the example closely it works fine, like all the other D3 SVG examples I’ve seen the SVG element is created by D3.
The change I’ve made that’s giving me trouble, is done with a view to slotting multiple D3 graphics into a layout which is defined in static HTML.
When I experiment with getting D3 to add elements to an SVG tag already defined in the HTML:
the result is close but not always close enough.
Inspecting the DOM elements created, the difference is clear to see.
The code that works properly code includes:
var svgGraphic = d3.select("body").append("svg")
.attr("width", totalWidth)
.attr("height", totalHeight)
.append("g").attr("transform", "translate(80,0)");
This (plus a few lines not shown here) results in DOM elements in a hierarchy similar to the following:
<svg width="600" height="200">
<g transform="translate(80,0)">
<path class="link" d="M0,100C95,100 95,50 190,50">
<path class="link" d="M0,100C95,100 95,150 190,150">
<g class="node" transform="translate(0,100)">
<g class="node" transform="translate(190,50)">
<g class="node" transform="translate(380,25)">
</g>
</svg>
When the code is more like:
var svgGraphic = d3.select("#graphic");
svgGraphic.append("g").attr("transform", "translate(80,0)");
The path and node elements are NOT nested inside the first “g” tag:
<svg id="graphic" height="200" width="600">
<g transform="translate(80,0)">
<path class="link" d="M0,100C95,100 95,50 190,50">
<path class="link" d="M0,100C95,100 95,150 190,150">
<g class="node" transform="translate(0,100)">
<g class="node" transform="translate(190,50)">
<g class="node" transform="translate(380,25)">
</svg>
Clearly I’ve made no attempt to append the closing g tag but how does it get there in the first example ?
In the first case:
svgGraphicwill hold a reference to thegelement you appended in the last line.In the second case:
svgGraphicrefers to thesvgelement you selected withd3.select("#graphic").So if you append elements to
svgGraphic, they will be appended to thegelement in the first case and thesvgelement in the second case.I believe you want: