Skip to content

Instantly share code, notes, and snippets.

@mbostock
Forked from mbostock/.block
Last active October 22, 2018 01:30
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/4248146 to your computer and use it in GitHub Desktop.
Hexagonal Binning (Area)
license: gpl-3.0
redirect: https://beta.observablehq.com/@mbostock/d3-hexbin-area

This example shows how to use the d3-hexbin plugin for hexagonal binning. 2,000 random points with a normal distribution are binned into hexagons; area encodes the number of points that fall into each bin. You can also use color encoding.

<!DOCTYPE html>
<style>
.hexagon {
fill: steelblue;
stroke: #fff;
stroke-width: 0.5px;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var randomX = d3.randomNormal(width / 2, 80),
randomY = d3.randomNormal(height / 2, 80),
points = d3.range(2000).map(function() { return [randomX(), randomY()]; });
var radius = d3.scaleSqrt()
.domain([0, 50])
.range([0, 20]);
var hexbin = d3.hexbin()
.radius(20)
.extent([[0, 0], [width, height]]);
var x = d3.scaleLinear()
.domain([0, width])
.range([0, width]);
var y = d3.scaleLinear()
.domain([0, height])
.range([height, 0]);
g.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
g.append("g")
.attr("class", "hexagon")
.attr("clip-path", "url(#clip)")
.selectAll("path")
.data(hexbin(points))
.enter().append("path")
.attr("d", function(d) { return hexbin.hexagon(radius(d.length)); })
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y).tickSizeOuter(-width));
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).tickSizeOuter(-height));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment