What is the difference between these two code blocks in d3.js

I thought the d3.js append function returns an object added to the selection, but I found that the following two blocks of code give different results:

 var svg = d3.select("body") .append("svg") .attr("width", fig_width) .attr("height", fig_height); svg.append("g") .attr("class", "graph") .attr("transform", "translate(" + graph_margin.left + "," + graph_margin.top + ")"); 

Which, it seems, does not translate the group of graphs, compensating for it with the left and top edges and:

 var svg = d3.select("body") .append("svg") .attr("width", fig_width) .attr("height", fig_height) .append("g") .attr("class", "graph") .attr("transform", "translate(" + graph_margin.left + "," + graph_margin.top + ")"); 

which does.

What I donโ€™t understand about how this works in SVG / d3.js?

+5
source share
1 answer

Both blocks of code should produce exactly the same result.

I assume that you are using svg to add additional elements - remember that in the first case, svg contains the SVG element, and in the second - the translated g element. So, everything that you added to svg in the first case would not be translated (since the new elements are not contained in the g element).

+2
source

All Articles