Skip to content

Instantly share code, notes, and snippets.

@asuozzo
Last active November 4, 2019 15:50
Show Gist options
  • Save asuozzo/895284cf0426ff09f4f7f225708827c8 to your computer and use it in GitHub Desktop.
Save asuozzo/895284cf0426ff09f4f7f225708827c8 to your computer and use it in GitHub Desktop.
Beeswarm
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.axis text {
font: 10px sans-serif;
}
.cells path {
fill: none;
pointer-events: all;
}
.cells circle {
stroke-width:.5;
}
svg .annotation {
stroke-dasharray:4;
stroke:gray;
}
</style>
<svg id="facilityScores" width="100%" height="100"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var scores = [
{"value":4},{"value":6},{"value":520},{"value":3},{"value":10},{"value":3}
]
var score = 520;
var scoreSvg = d3.select("#facilityScores")
var drawScoreChart = function(){
var margin = {top: 40, right: 40, bottom: 40, left: 40},
height = scoreSvg.attr("height") - margin.top - margin.bottom;
var formatValue = d3.format(",d");
var max = d3.max(scores, function(d){return d.value;});
var colorScale = d3.scaleLinear().domain([-20,520]).range(['#fff', '#a51b02']);
scoreSvg.selectAll("*").remove();
var width = parseInt(scoreSvg.style('width')) - margin.left - margin.right;
var x = d3.scaleLinear()
.rangeRound([0, width]);
var g = scoreSvg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(d3.extent(scores, function(d) { return d.value; }));
var simulation = d3.forceSimulation(scores)
.force("x", d3.forceX(function(d) { return x(d.value); }).strength(3))
.force("y", d3.forceY(height / 2))
.force("collide", d3.forceCollide(4))
.stop();
for (var i = 0; i < 120; ++i) simulation.tick();
var cell = g.append("g")
.attr("class", "cells")
.selectAll("g").data(d3.voronoi()
.extent([[-margin.left, -margin.top], [width + margin.right, height + margin.top]])
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.polygons(scores)).enter().append("g");
cell.append("circle")
.attr("r", 3.5)
.attr("cx", function(d) { return d.data.x; })
.attr("cy", function(d) {
return d.data.y; })
.style("fill",function(d){
return colorScale(d.data.value);
}).style(
"stroke","lightgray"
);
cell.append("path")
.attr("d", function(d) { return "M" + d.join("L") + "Z"; });
g.append("line")
.attr("x1", function(d){
return x(score)
})
.attr("y1", -10)
.attr("x2", function(d){
return x(score)
})
.attr("y2", height)
.attr("class","annotation")
.style("stroke","black")
}
d3.select(window).on('resize', drawScoreChart);
drawScoreChart();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment