Skip to content

Instantly share code, notes, and snippets.

@gavlooth
Last active October 28, 2017 05:36
Show Gist options
  • Save gavlooth/3f82df9f9b451a372a2079e763fcbaec to your computer and use it in GitHub Desktop.
Save gavlooth/3f82df9f9b451a372a2079e763fcbaec to your computer and use it in GitHub Desktop.
Show National Contiguity with a Force Directed Graph
<div id="graph">
</div>
$(document).ready(function() {
$.getJSON('https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json',
function(data) {
const yu = "https://upload.wikimedia.org/wikipedia/commons/7/71/Flag_of_SFR_Yugoslavia.svg",
Url = 'https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.5.0/flags/1x1/',
width = 1000,
height = 500,
r = 5,
sqrWidth = 12,
sqrheight = 8;
let graph = d3.select('#graph').append('svg')
.attr('width', width)
.attr('height', height);
let simulation = d3.forceSimulation()
.nodes(data.nodes)
.force("link", d3.forceLink().distance(10).strength(0.2))
.force("charge", d3.forceManyBody().strength(-30))
.force("center", d3.forceCenter(width / 2, height / 2))
.force("x", d3.forceX())
.force("y", d3.forceY())
.on("tick", ticked);
simulation.force("link")
.links(data.links);
let link = graph.append("g")
.attr("class", "links")
.selectAll("line")
.data(data.links)
.enter().append("line")
.attr("stroke-width", 1);
let node = graph.append("g")
.attr("class", "nodes")
.selectAll("image")
.data(data.nodes)
.enter().append("image")
.attr("width", sqrWidth)
.attr("height", sqrheight)
.attr("xlink:href", d => d.code == "xk" ? yu : Url + d.code + ".svg")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
/* let node = graph.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(data.nodes)
.enter().append("circle")
.attr("r", r)
.attr("fill", "#B2C248")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));*/
node.append("title")
.text(d => d.country);
function ticked() {
link
.attr("x1", d => d.source.x + sqrWidth / 2)
.attr("y1", d => d.source.y + sqrheight / 2)
.attr("x2", d => d.target.x + sqrWidth / 2)
.attr("y2", d => d.target.y + sqrheight / 2);
node
.attr("x", d => d.x)
.attr("y", d => d.y);
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
function PointGravity(alpha) {
for (let i = 0, n = data.nodes.length, node, k = alpha * 0.1; i < n; ++i) {
node = data.nodes[i];
node.vx -= node.x * k;
node.vy -= node.y * 50 * k;
}
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
.links line {
stroke: black;
stroke-opacity: 0.6;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment