D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
yanhann10
Full window
Github gist
forcelayout
Built with
blockbuilder.org
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>D3: Force layout</title> <script src="https://d3js.org/d3.v4.min.js"></script> <style type="text/css"> /* No style rules here yet */ </style> </head> <body> <script type="text/javascript"> //Width and height var w = 800; var h = 500; //Original data url='https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json' d3.json(url, function(error, dataset) { //Initialize a simple force layout, using the nodes and links in dataset var force = d3.forceSimulation(dataset.nodes) .force("charge", d3.forceManyBody()) .force("link", d3.forceLink(dataset.links)) .force("center", d3.forceCenter().x(w/2).y(h/2)); var colors = d3.scaleOrdinal(d3.schemeCategory10); //Create SVG element var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); //Create links as lines var links = svg.selectAll("line") .data(dataset.links) .enter() .append("line") .style("stroke", "#ccc") .style("stroke-width", 1); //Create nodes as circles var nodes = svg.selectAll("circle") .data(dataset.nodes) .enter() .append("circle") .attr("r", 10) .style("fill", function(d, i) { return colors(i); }) .call(d3.drag() //Define what to do on drag events .on("start", dragStarted) .on("drag", dragging) .on("end", dragEnded));; //Add a simple tooltip nodes.append("title") .text(function(d) { return d.name; }); //Every time the simulation "ticks", this will be called force.on("tick", function() { links.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; }); nodes.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); }); function dragStarted(d) { if (!d3.event.active) force.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; } function dragging(d) { d.fx = d3.event.x; d.fy = d3.event.y; } function dragEnded(d) { if (!d3.event.active) force.alphaTarget(0); d.fx = null; d.fy = null; } }); </script> </body> </html>
https://d3js.org/d3.v4.min.js