Skip to content

Instantly share code, notes, and snippets.

@mgax
Last active August 29, 2015 14:24
Show Gist options
  • Save mgax/d557e198527c394ba856 to your computer and use it in GitHub Desktop.
Save mgax/d557e198527c394ba856 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node circle {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
stroke-opacity: .6;
}
text {
pointer-events: none;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var width = 960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(80)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
setTimeout(function() {
var links = [];
var skills = ['a', 'b', 'c'];
people.forEach(function(p1, n1) {
console.log(p1);
people.forEach(function(p2, n2) {
if(n2 <= n1) return;
var like = d3.sum(skills, function(s) {
s1 = p1.skills[s];
s2 = p2.skills[s];
if(s1*s2 < 0) {
return Math.abs(s1 - s2);
}
});
if(like > 4) {
var link = {
source: n1,
target: n2,
value: like,
};
links.push(link);
console.log(link);
}
});
});
graph = {nodes: people, links: links};
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append('g')
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); });
node.append('text')
.text(function(d) { return d.name; });
force.on("tick", function() {
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('transform', function(d) {
return 'translate(' + [d.x, d.y] + ')';
});
});
}, 0);
var people = [
{name: "one", skills: {a: -3, b: 0, c: 3}},
{name: "two", skills: {a: 0, b: 2, c: 1}},
{name: "three", skills: {a: 3, b: -2, c: -3}},
{name: "four", skills: {a: 2, b: 2, c: 0}},
{name: "five", skills: {a: 1, b: -3, c: 2}},
{name: "six", skills: {a: -2, b: 0, c: -1}},
];
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment