Skip to content

Instantly share code, notes, and snippets.

@darrenjaworski
Created March 4, 2015 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrenjaworski/742c0864c409e9202982 to your computer and use it in GitHub Desktop.
Save darrenjaworski/742c0864c409e9202982 to your computer and use it in GitHub Desktop.
Angular D3 force directed graph
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
margin: 0;
height: 100%;
width: 100%;
position: absolute;
}
network-graph {
height: 300px;
width: 300px;
float: left;
}
.node {
stroke-width: 1.5px;
}
</style>
<body ng-app="myApp" ng-controller="myAppController">
<network-graph data="graph" ng-repeat="graph in graphs"></network-graph>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', [])
app.controller('myAppController', function($scope){
$scope.graphs = d3.range(5).map(function(i){
return d3.range(10).map(function() {
return {
id: ~~(Math.random() * 3),
index: i,
size: ~~(Math.random() * (12 - 4) + 4),
party: ~~(Math.random() * 2)
}
})
})
})
app.directive('networkGraph', function(){
function link(scope, el) {
var el = el[0],
width = el.clientWidth,
height = el.clientHeight,
votefoci = [
{x: width / 2, y: height / 10},
{x: width / 10, y: 2 * height / 3 },
{x: width, y: 2 * height / 3}
];
var fill = d3.scale.linear()
.range(["#00aff3", "#d8171e"]);
var nodes = scope.data;
var force = d3.layout.force()
.nodes(nodes)
.size([width, height])
.on("tick", tick)
.start();
var svg = d3.select(el).append("svg")
.attr("width", width)
.attr("height", height);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", function(d) { return d.size; })
.style("fill", function(d, i) { return fill(d.party); })
.style("stroke", function(d, i) { return d3.rgb(fill(d.party)).darker(2); })
.call(force.drag);
svg.style("opacity", 1e-6)
.transition()
.duration(1000)
.style("opacity", 1);
function tick(e) {
// Push different nodes in different directions for clustering.
var k = .1 * e.alpha;
nodes.forEach(function(o, i) {
o.y += (votefoci[o.id].y - o.y) * k;
o.x += (votefoci[o.id].x - o.x) * k;
});
node
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
}
return {
link: link,
restrict: 'E',
scope: { data: '='}
}
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment