In response to a Stack Overflow question, How to convert to D3's JSON format?.
-
-
Save rubenfilteris/3082680 to your computer and use it in GitHub Desktop.
Force Layout from CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source | target | |
---|---|---|
A1 | A2 | |
A2 | A3 | |
A2 | A4 | |
B1 | B2 | |
B2 | B3 | |
B3 | B4 | |
B4 | B5 | |
B5 | B6 | |
B6 | B1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.link { | |
stroke: #000; | |
} | |
.node { | |
stroke: #fff; | |
} | |
</style> | |
<body> | |
<script src="http://d3js.org/d3.v2.js?2.9.3"></script> | |
<script> | |
var width = 960, | |
height = 500; | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
var force = d3.layout.force() | |
.size([width, height]); | |
d3.csv("graph.csv", function(links) { | |
var nodesByName = {}; | |
// Create nodes for each unique source and target. | |
links.forEach(function(link) { | |
link.source = nodeByName(link.source); | |
link.target = nodeByName(link.target); | |
}); | |
// Extract the array of nodes from the map by name. | |
var nodes = d3.values(nodesByName); | |
// Create the link lines. | |
var link = svg.selectAll(".link") | |
.data(links) | |
.enter().append("line") | |
.attr("class", "link"); | |
// Create the node circles. | |
var node = svg.selectAll(".node") | |
.data(nodes) | |
.enter().append("circle") | |
.attr("class", "node") | |
.attr("r", 4.5) | |
.call(force.drag); | |
// Start the force layout. | |
force | |
.nodes(nodes) | |
.links(links) | |
.on("tick", tick) | |
.start(); | |
function tick() { | |
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; }); | |
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}); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment