You can write the generateMultiForce function as a jquery plugin - this apparently preserves independent graphics and applies a force layout to both:
var width = 600, height = 600; var color = d3.scale.category20(); var data = [ { "nodes": [ {"name": "Hello"}, {"name": "World"} ], "links": [ {"source": 0, "target": 1, "value": 0.5} ] }, { "nodes": [ {"name": "Zero"}, {"name": "One"}, {"name": "Two"} ], "links": [ {"source": 0, "target": 1, "value": 0.25}, {"source": 1, "target": 2, "value": 0.5}, {"source": 2, "target": 0, "value": 0.25} ] } ]; (function( $ ) { $.fn.generateMultiForce = function(svgObj) { return this.each(function() { var graph = this; var graphArea = svgObj.append("g"); var force = d3.layout.force() .charge(-200) .linkDistance(45) .size([width, height]) .nodes(graph.nodes) .links(graph.links) .start(); var link = graphArea.selectAll(".link") .data(graph.links) .enter().append("line") .attr("class", "link"); var nodeGroup = graphArea.selectAll("g") .data(graph.nodes) .enter().append("g") .call(force.drag); var node = nodeGroup.append("circle") .attr("class", "node") .attr("r", 5) .style("fill", function(d) { return color(d.group); }); var text = nodeGroup.append("text") .attr("x", 8) .attr("y", ".31em") .text(function(d) { return d.name; }); force.on("tick", function() { link .attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); nodeGroup.attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; }); }); }); }; })(jQuery); var svgTest = d3.select("body").append("svg") .attr("width", width) .attr("height", height); $(data).generateMultiForce(svgTest);
source share