Skip to content

Instantly share code, notes, and snippets.

@jwilber
Last active July 16, 2020 05:47
Show Gist options
  • Save jwilber/0ef2e6600f752258b38a6ad8326d40b9 to your computer and use it in GitHub Desktop.
Save jwilber/0ef2e6600f752258b38a6ad8326d40b9 to your computer and use it in GitHub Desktop.
force basic dot plot
license: mit

Basic dot-plot using force-directed layout.

<!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; }
</style>
</head>
<body>
<script>
const width = 1000
const height = 600
const svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
const roleScale = d3.scaleOrdinal()
.range(['coral', 'olive', 'skyblue', 'pink']);
let sampleData = d3.range(8).map((d,i) => ({r: 40 - i * 0.5}));
const radiusScale = d3.scaleLinear()
.domain(d3.extent(sampleData, d => d.r))
.range([20, 50])
// set params for force layout
const manyBody = d3.forceManyBody().strength(2)
const center = d3.forceCenter().x((width/2)).y((height/2))
// define force
let force = d3.forceSimulation()
.force('charge', manyBody)
.force('center', center)
.force('collision', d3.forceCollide(d => d.r-4))
.velocityDecay(.48)
.nodes(sampleData)
.on('tick', changeNetwork)
svg.selectAll('circle')
.data(sampleData)
.enter()
.append('circle')
.attr('class', 'node')
.style('fill', (d,i) => roleScale(i))
.attr('r', d => radiusScale(d.r))
function changeNetwork() {
d3.selectAll('circle')
.attr('cx', d => d.x)
.attr('cy', d => d.y)
}
d3.selectAll('circle.node')
.on('mouseover', function() {
d3.select(this)
.style('stroke', 'black')
.style('stroke-width', 4)
.raise()
})
.on('mouseout', function() {
d3.select(this)
.style('stroke-width', 0)
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment