|
<html> |
|
<head> |
|
<title>Drawing reciprocal edges</title> |
|
<meta charset="utf-8" /> |
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> |
|
</head> |
|
<style> |
|
svg { |
|
height: 500px; |
|
width: 500px; |
|
border: 1px solid gray; |
|
} |
|
</style> |
|
<body> |
|
|
|
<div id="viz"> |
|
<svg> |
|
</svg> |
|
</div> |
|
</body> |
|
<footer> |
|
<script> |
|
|
|
d3.csv("firm.csv",function(error,data) {createNetwork(data)}); |
|
|
|
function createNetwork(edgelist) { |
|
var nodeHash = {}; |
|
var edgeHash = {}; |
|
var nodes = []; |
|
var edges = []; |
|
|
|
edgelist.forEach(function (edge) { |
|
if (!nodeHash[edge.source]) { |
|
nodeHash[edge.source] = {id: edge.source, label: edge.source}; |
|
nodes.push(nodeHash[edge.source]); |
|
} |
|
if (!nodeHash[edge.target]) { |
|
nodeHash[edge.target] = {id: edge.target, label: edge.target}; |
|
nodes.push(nodeHash[edge.target]); |
|
} |
|
|
|
//is it reciprocal? |
|
|
|
if (edge.weight >= 5) { |
|
if (edgeHash[edge.target + "-" + edge.source]) { |
|
edgeHash[edge.target + "-" + edge.source].reciprocal = true; |
|
} |
|
else { |
|
var newEdge = {source: nodeHash[edge.source], target: nodeHash[edge.target], weight: edge.weight}; |
|
edgeHash[edge.source + "-" + edge.target] = newEdge; |
|
edges.push(newEdge); |
|
} |
|
} |
|
}); |
|
createForceNetwork(nodes, edges); |
|
} |
|
|
|
function createForceNetwork(nodes, edges) { |
|
|
|
//create a network from an edgelist |
|
|
|
var force = d3.layout.force().nodes(nodes).links(edges) |
|
.size([500,500]) |
|
.charge(-200) |
|
.on("tick", updateNetwork); |
|
|
|
d3.select("svg").selectAll("line") |
|
.data(edges) |
|
.enter() |
|
.append("line") |
|
.style("stroke-width", "2px") |
|
.style("stroke", function (d) {return d.reciprocal ? "#66CCCC" : "#996666"}); |
|
|
|
d3.select("svg").selectAll("circle") |
|
.data(nodes) |
|
.enter() |
|
.append("circle") |
|
.style("fill", "#FFFF99") |
|
.style("stroke", "#666633") |
|
.style("stroke-width", "1px") |
|
.attr("r", 5) |
|
.call(force.drag()); |
|
|
|
force.start(); |
|
|
|
function updateNetwork() { |
|
d3.select("svg").selectAll("line") |
|
.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}); |
|
|
|
d3.select("svg").selectAll("circle") |
|
.attr("cx", function (d) {return d.x}) |
|
.attr("cy", function (d) {return d.y}); |
|
} |
|
|
|
|
|
|
|
} |
|
</script> |
|
</footer> |
|
|
|
</html> |