You are here: Home / Solutions / D3ForceLayout

D3ForceLayout

text/html D3ForceLayout.htm — 2 KB

File contents

<!DOCTYPE html>
<html style="" lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<meta charset="utf-8">
		<title>The Force Layout</title>
      <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
	</head>
	<body>
		<script type="text/javascript">

			//Width and height
			var w = 600;
			var h = 250;

			//Original data
			var dataset = {
				nodes: [
					{ name: "n0" },
					{ name: "n1" },
					{ name: "n2" },
					{ name: "n3" },
					{ name: "n4" },
					{ name: "n5" },
					{ name: "n6" },
					{ name: "n7" },
					{ name: "n8" },
					{ name: "n9" }
				],
				edges: [
					{ source: 0, target: 9 },
					{ source: 0, target: 2 },
					{ source: 0, target: 4 },
					{ source: 1, target: 5 },
					{ source: 2, target: 3 },
					{ source: 2, target: 5 },
					{ source: 3, target: 4 },
					{ source: 5, target: 8 },
					{ source: 5, target: 9 },
					{ source: 6, target: 7 },
					{ source: 7, target: 8 },
					{ source: 8, target: 9 }
				]
			};

			//Initialize a default force layout, using the nodes and edges in dataset
			var force = d3.layout.force()
								 .nodes(dataset.nodes)
								 .links(dataset.edges)
								 .size([w, h])
								 .linkDistance([75])
								 .charge([-100])
								 .start();

			var colors = d3.scale.category20();

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

			//Create edges as lines
			var edges = svg.selectAll("line")
				.data(dataset.edges)
				.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", 11)
				.style("fill", function(d, i) {
					return colors(i);
				})
				.call(force.drag);

			//Every time the simulation "ticks", this will be called
			force.on("tick", function() {

				edges.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; });

			});


		</script>


</body></html>