Groups and transformations

d3_groups_and_transformations.html ● d3.min.js ● data/fruit.csv

append("g")

In the fruits-example we have now two elements which belong together: the fruits and the axis. If we now manipulate their position (e.g. adding another axis on the left side) we would like to do that in one transformation for the axis and fruits at once.

SVGs provide the group element via the tag "g" to allow for group-wise manipulation of elements. Transformations can be applied to the group element (as to basic shapes) and affect all its children.

//Add the group and translate it
let diagram = svg.append("g").attr("transform","translate(20,0)")

//Appends the fruits to the group
diagram.selectAll("fruits")
.data(data)
.enter()
.append("circle") (...)

//Appends the axis to the group
diagram.append("g").call(axisX) (...)

Example

If you look at the code, it works exactly as we aspected:

More about transformations