Skip to content

Instantly share code, notes, and snippets.

@mroswell
Created December 5, 2013 17:08
Show Gist options
  • Save mroswell/7809304 to your computer and use it in GitHub Desktop.
Save mroswell/7809304 to your computer and use it in GitHub Desktop.
social-graph.js
var VIZ = {};
VIZ.w = 700;
VIZ.h = 400;
friendNetwork = [
{ "Tom": ["Mary", "Adam", "Brian"]},
{ "Mary": ["Tom", "Jane", "Adam", "Elizabeth", "Brian", "Mary"]},
{ "Jane": ["Mary", "Peter", "Kimberly", "Emily", "Laura"]},
{ "Adam": ["Mary", "Tom", "Karen"]},
{ "Peter": ["Mary", "Jane"]},
{ "Elizabeth": ["Jennifer", "Mary"]},
{ "Jennifer": ["Elizabeth"]},
{ "Linda": ["Barbara"]},
{ "Barbara": ["Linda" ]},
{ "Jessica": ["Dorothy"]},
{ "Dorothy": ["Jessica"]},
{ "Sarah": ["Karen"] },
{ "Karen": ["Sarah", "Adam"]},
{ "Kimberly": ["Jane"]},
{ "Emily": ["Jane"]},
{ "Laura": ["Jane", "Andrew"]},
{ "Andrew": ["Laura"]},
{ "Brian": ["Mary", "Tom", "Timothy"]},
{ "Timothy": ["Tom", "Brian", "Donna"]},
{ "Donna": ["Timothy","Mary"]}
];
var dataset = {
nodes: [],
edges: []
};
function createNodeArray(person, personIndex, network) {
var personName = _.keys(person)[0];
var nodeObject = {node: personName};
dataset.nodes.push(nodeObject);
// for every person, figure out what friends they have
var friends = network[personIndex][personName];
// for every friend (for every person) figure out what the friend's index is
_.each(friends, function(friendName) {
// for each friend find the object whose key matches the friendName
// console.log("friend", friendName,";", "person:", personName);
_.each(network, function (possibleFriendObject, possibleFriendIndex) {
var possibleFriendName = _.keys(possibleFriendObject)[0];
if(possibleFriendName===friendName){
var newEdge = {
source: personIndex,
target: possibleFriendIndex
};
// for every combination of person-index and possibleFriendindex, push the object to dataset.edges
dataset.edges.push(newEdge);
}
});
});
}
_.each(friendNetwork, createNodeArray);
var svg = d3.select("body")
.append("svg")
.attr("width", VIZ.w)
.attr("height", VIZ.h)
.attr("class", "forceClass");
var force = d3.layout.force()
.nodes(dataset.nodes)
.links(dataset.edges)
.size([VIZ.w, VIZ.h])
.linkDistance([100])
.charge([-300])
.start();
var nodes = svg.selectAll("circle")
.data(dataset.nodes)
.enter()
.append("circle")
.attr("r", 10)
.call(force.drag);
var edges = svg.selectAll("line")
.data(dataset.edges)
.enter()
.append("line");
force.on("tick", function(){
edges.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; });
nodes.attr("cx", function(d){ return d.x; })
.attr("cy", function(d){ return d.y; });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment