Triangular binning a set of 2D points. Maps color to the density of points within a triangle.
Essentially a fork of this block that does hexagonal binning. Uses the d3.triangleBin plugin. Also see this block which maps density to area instead of color.
xxxxxxxxxx
<html>
<head>
<style>
body {
font: 12px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
}
.triangle {
fill: none;
stroke: #ddd;
stroke-width: 0.5px;
}
</style>
</head>
<body>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="triangle-bin.js"></script>
<script>
var margin = { top: 10, left: 40, bottom: 30, right: 10 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var points = d3.range(2000)
.map(function() {
return [
d3.random.normal(width/2, 80)(),
d3.random.normal(height/2, 80)()
];
});
var xScale = d3.scale.identity().domain([0, width]),
yScale = d3.scale.linear()
.domain([0, height])
.range([height, 0]);
var xAxis = d3.svg.axis().scale(xScale).orient("bottom"),
yAxis = d3.svg.axis().scale(yScale).orient("left");
var color = d3.scale.linear()
.domain([0, 20])
.range(["white", "steelblue"])
.interpolate(d3.interpolateLab);
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 + ")");
var tribin = d3.triangleBin()
.size([width, height])
.sideLength(35);
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("clip-path", "url(#clip)")
.selectAll(".triangle")
.data(tribin(points))
.enter().append("path")
.attr("class", "triangle")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
.attr("d", function(d) { return tribin.triangle(d.orientation); })
.style("fill", function(d) { return color(d.length); });
svg.append("g").call(xAxis)
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")");
svg.append("g").call(yAxis)
.attr("class", "y axis");
</script>
</body>
</html>
https://d3js.org/d3.v3.min.js