Skip to content

Instantly share code, notes, and snippets.

@oliviac12
Last active December 8, 2016 02:14
Show Gist options
  • Save oliviac12/cffd2f0c7c5de2782fa4c0ddf64febaa to your computer and use it in GitHub Desktop.
Save oliviac12/cffd2f0c7c5de2782fa4c0ddf64febaa to your computer and use it in GitHub Desktop.
A force-directed Graph of Relationships
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke-opacity: .6;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 960;
var height = 500;
var radius = 5;
var colors =d3.scaleOrdinal(d3.schemeCategory10);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json('links.json', function(err, data){
// console.log(data);
//position node with their group
// var perRow = 2;
// data.nodes.forEach(function(node){
// node.focusX = (node.group % perRow)* 100;
// node.focusY = Math.floor(node.group/ perRow) * 100;
// });
data.links.forEach(function(link) {
link.source = data.nodes.find(function(node) {return node.id === link.source});
link.target = data.nodes.find(function(node) {return node.id === link.target});
});
// one tick it's one iteration
var simulations = d3.forceSimulation(data.nodes)
.force('center', d3.forceCenter(width/2, height/2))
.force('collide', d3.forceCollide(radius + 1))
// .force('attraction', d3.forceManyBody().strength(100).distanceMin(150))
// .force('repulsion', d3.forceManyBody().strength(-100).distanceMax(150))
.force('x', d3.forceX().x(function(d){
return d.focusX
}))
.force('y', d3.forceY().y(function(d){
return d.focusY }))
// .force('links', d3.forceLink(data.links)
// .id(function(d){return d.id})
// .strength(function(d){})
.on('tick', ticked);
//create circle for each node, there's x and y got calculated each tick
var links = svg.selectAll('line')
.data(data.links, function(d){return d.source.id + ',' + d.target.id})
.enter().append('line')
.attr('stroke', '#ccc');
var circles = svg.selectAll('circle')
.data(data.nodes, function(d){return d.id})
.enter().append('circle')
.attr('r', radius)
.attr('fill', function(d){return colors(d.group)})
// .call(drag)
function ticked() {
circles
.attr('cx', function(d) {return d.x})
.attr('cy', function(d) {return d.y});
links.attr('x1', function(d) {return d.source.x})
.attr('x2', function(d){return d.target.x})
.attr('y1', function(d) {return d.source.y})
.attr('y2', function(d){return d.target.y})
}
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment