Groups as Nodes in Force Layout

http://stackoverflow.com/questions/22737129/d3-force-layout-with-groups-as-nodes

by Nivaldo

JavaScript

function addCircles(sel) {
    sel.selectAll("circle")
        .data([1,2,3])
        .enter()
        .append("circle")
        .attr("cx", function(d) { return d * 10; })
        .attr("cy", function(d) { return d * 10; })
        .attr("r", 3);
}

var w = h = 500;

var svg = d3.select("body").append("svg").attr("width", w).attr("height", h);

var nodes = [{}, {}, {}];

var force = d3.layout.force()
    .size([w, h])
    .nodes(nodes)
    .charge(-100)
    .on("tick", tick)
    .start();

svg.selectAll("g.node")
    .data(nodes)
    .enter()
    .append("g")
    .attr("class", "node")
    .call(addCircles)
    .call(force.drag);

function tick() {
    svg.selectAll("g.node")
        .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}