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. Inspired by earlier work by Zachary Forest Johnson.
forked from mbostock's block: Hexagonal Binning (Area)
xxxxxxxxxx
<meta charset="utf-8">
<style>
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.hexagon {
fill: steelblue;
stroke: #fff;
stroke-width: .5px;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="d3.hexbin.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
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()
.size([width, height])
.radius(20);
var x = d3.scaleIdentity()
.domain([0, width]);
var y = d3.scaleLinear()
.domain([0, height])
.range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x)
.tickSize(6, -height);
var yAxis = d3.axisLeft()
.scale(y)
.tickSize(6, -width);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("class", "mesh")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("clip-path", "url(#clip)")
.selectAll(".hexagon")
.data(hexbin(points))
.enter().append("path")
.attr("class", "hexagon")
.attr("d", function(d) { return hexbin.hexagon(radius(d.length)); })
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
</script>
https://d3js.org/d3.v4.min.js