Built with blockbuilder.org
Last active
October 8, 2018 06:17
-
-
Save jwilber/9546fedd3fc4951fc2bbf4bc3970fbc7 to your computer and use it in GitHub Desktop.
force-directed distribution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; background-color:black; } | |
svg { background-color: black;} | |
</style> | |
</head> | |
<body> | |
<script> | |
const width = 1000 | |
const height = 500 | |
const svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height) | |
.append('g') | |
.attr('transform', 'translate()') | |
const colorScale = d3.scaleOrdinal() | |
.range(['#FCFCFC', 'coral', '#FFFAE3', '#99E1D9', 'skyblue']) | |
const radius = 7 | |
const sampleData = d3.range(600).map(() => ({r: radius, | |
value: width/2 + d3.randomNormal(0,2.8)() * 50})) | |
// define force | |
let force = d3.forceSimulation() | |
.force('collision', d3.forceCollide(d => d.r+1).strength(1)) | |
.force('x', d3.forceX(d => d.value).strength(3)) | |
.force('y', d3.forceY(height - radius).strength(0.05)) | |
.nodes(sampleData) | |
.on('tick', changeNetwork) | |
svg.selectAll('circle') | |
.data(sampleData) | |
.enter() | |
.append('circle') | |
.style('fill', (d,i) => colorScale(i)) | |
.attr('r', d => d.r) | |
.attr('stroke', 'white') | |
.attr('stroke-width', .1) | |
function changeNetwork() { | |
d3.selectAll('circle') | |
.attr('cx', d => d.x) | |
.attr('cy', d => d.y = Math.min(d.y, height - radius - 1)) | |
} | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment