Skip to content

Instantly share code, notes, and snippets.

@4xDMG
Created June 6, 2017 04:06
Show Gist options
  • Save 4xDMG/f061c955e7ebae250fa0b3ffe291b195 to your computer and use it in GitHub Desktop.
Save 4xDMG/f061c955e7ebae250fa0b3ffe291b195 to your computer and use it in GitHub Desktop.
force-simulation
license: mit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.js"></script>
<link rel="stylesheet" href="//rawgithub.com/Caged/d3-tip/master/examples/example-styles.css">
<title>National Contiguity</title>
<style>
body {
margin: 0;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
svg {
width: 100%;
height: 100%;
}
.d3-tip {
max-width: 300px;
}
.links line {
stroke: #000;
stroke-opacity: 0.6;
}
.nodes circle {
stroke: #fff;
stroke-width: 1.5px;
}
</style>
</head>
<body>
<svg width="1200px" height="600px"></svg>
<script>
fetch('https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json')
.then(response => response.json())
.then(data => {
const height = 600;
const width = 1200;
const svg = d3.select('svg');
const nationSimulation = d3.forceSimulation(data.nodes)
.force('link', d3.forceLink(data.links).id(d => d.index))
.force('charge', d3.forceManyBody())
.force('center', d3.forceCenter(width/2, height/2));
const link = svg.append('g')
.selectAll('line')
.data(data.links)
.enter().append('line')
.attr('class', 'links')
.attr('stroke-width', 2)
.attr('stroke', 'black');
const node = svg.append('g')
.selectAll('circle')
.data(data.nodes)
.enter().append('circle')
.attr('class', 'nodes')
.attr('r', 5)
.attr('fill', 'blue');
function tickActions() {
node
.attr('cx', d => d.x)
.attr('cy', d => d.y);
link
.attr('x1', d => d.source.x)
.attr('y1', d => d.source.y)
.attr('x2', d => d.target.x)
.attr('y2', d => d.target.y);
}
nationSimulation.on('tick', tickActions);
console.log(data);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment