Skip to content

Instantly share code, notes, and snippets.

Last active November 8, 2019 07:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save mbostock/2949937 to your computer and use it in GitHub Desktop.
Save mbostock/2949937 to your computer and use it in GitHub Desktop.
Force Layout from CSV
license: gpl-3.0
source target
A1 A2
A2 A3
A2 A4
<!DOCTYPE html>
<meta charset="utf-8">
.link {
stroke: #000;
.node {
stroke: #fff;
<script src="//"></script>
var width = 960,
height = 500;
var svg ="body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.size([width, height]);
d3.csv("graph.csv", function(error, links) {
if (error) throw error;
var nodesByName = {};
// Create nodes for each unique source and target.
links.forEach(function(link) {
link.source = nodeByName(link.source); = nodeByName(;
// Extract the array of nodes from the map by name.
var nodes = d3.values(nodesByName);
// Create the link lines.
var link = svg.selectAll(".link")
.attr("class", "link");
// Create the node circles.
var node = svg.selectAll(".node")
.attr("class", "node")
.attr("r", 4.5)
// Start the force layout.
.on("tick", tick)
function tick() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return; })
.attr("y2", function(d) { return; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
function nodeByName(name) {
return nodesByName[name] || (nodesByName[name] = {name: name});
Copy link

Hi, I've search for sample to show only source nodes when loading the graph. When click on the source node, then the target node will be display. Do you have sample code for that and willing to share.

Copy link

This is pretty much exactly what I've been looking for to begin my project of mapping my learning in a concise and meaningful way.

All I need is 1 addition and that is the capacity to include text in the nodes, this is a great starting point thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment