Note that var svg
assigned to <g>
nested inside <svg>
svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") // <-- This is what svg is currently being assigned to .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
So, when you later do var legend = svg.append("g")
, you are actually adding the legend as a child of the above <g>
. And this is what you described seeing in dev tools.
One of the consequences is that the translate()
transformation that you applied to the external <g>
affects the internal <g>
(i.e. the translation of the main <g>
of legend
added to the translation of the external <g>
).
You probably want to separate things like this:
var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom); var inner = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
Then modify your code to draw an existing diagram in inner
, not svg
.
As a result, var legend = svg.append("g")
will add the legend as the sibling of inner
, and any translation you apply to legend
will refer to the upper left upper corner of svg (unlike inner
at the top left, which is translated by margin
)
And probably you want to translate legend
like this:
var legend = svg.append("g") .attr("transform", "translate(" + width - margin.right + "," + margin.top + ")");
This moves the legend to the right end of the chart, MINUS margin.right
. That way you can customize margin.right
to create enough space for legend
.
Finally, note that the call
legend .attr("height", 300) .attr("width", 200)
does nothing, because for svg <g>
there is no way to explicitly set the width and height. In any case, this does not mean much, because svg does not have the "streaming" behavior of html layouts. The width and height shown in dev tools are implicit bounds associated with the bounds of <g>
child elements. (If necessary, there is a way to get these calculated grades in javascript using the getBBox()
function).