Using alpha shapes to group or "encircle" sets of points.
It's not fast, but it's fun.
DISCLAIMER: this code is quite hackish, don't copy it blindly.
TODO: buffer the shapes so that they nicely enclose dots as ggplot2's geom_encircle function does.
The scatterplot matrix visualizations pairwise correlations for multi-dimensional data; each cell in the matrix is a scatterplot. This example uses Anderson's data of iris flowers on the Gaspé Peninsula. Scatterplot matrix design invented by J. A. Hartigan; see also R and GGobi. Data on Iris flowers collected by Edgar Anderson and published by Ronald Fisher.
S Forked from mbostock’s Scatterplot Matrix Brushing.
xxxxxxxxxx
<meta charset="utf-8">
<style>
svg {
font: 10px sans-serif;
padding: 10px;
}
.axis,
.frame {
shape-rendering: crispEdges;
}
.axis line {
stroke: #ddd;
}
.axis path {
display: none;
}
.cell text {
font-weight: bold;
text-transform: capitalize;
fill: black;
}
.frame {
fill: none;
stroke: #aaa;
}
circle {
fill-opacity: .7;
}
circle.hidden {
fill: #ccc !important;
}
.extent {
fill: #000;
fill-opacity: .125;
stroke: #fff;
}
.contour {
stroke-width: 1.5;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
<script>
// Computes boundaries of connected triangles, given an array of triangles.
// Jason Davies - https://bl.ocks.org/jasondavies/1554783
function boundary(mesh) {
console.log(mesh)
var counts = {},
edges = {},
r,
result = [];
// Traverse the edges of all triangles and discard any edges that appear twice.
mesh.forEach(function(triangle) {
for (var i = 0; i < 3; i++) {
var edge = [triangle[i], triangle[(i + 1) % 3]].sort(ascendingCoords).map(String);
(edges[edge[0]] = (edges[edge[0]] || [])).push(edge[1]);
(edges[edge[1]] = (edges[edge[1]] || [])).push(edge[0]);
var k = edge.join(":");
if (counts[k]) delete counts[k];
else counts[k] = 1;
}
});
while (1) {
var k = null;
// Pick an arbitrary starting point on a boundary.
for (k in counts) break;
if (k == null) break;
result.push(r = k.split(":").map(function(d) { return d.split(",").map(Number); }));
delete counts[k];
var q = r[1];
while (q[0] !== r[0][0] || q[1] !== r[0][1]) {
var p = q,
qs = edges[p.join(",")],
n = qs.length;
for (var i = 0; i < n; i++) {
q = qs[i].split(",").map(Number);
var edge = [p, q].sort(ascendingCoords).join(":");
if (counts[edge]) {
delete counts[edge];
r.push(q);
break;
}
}
}
}
return result;
}
function ascendingCoords(a, b) {
return a[0] === b[0] ? b[1] - a[1] : b[0] - a[0];
}
function alphashape(sites, alpha){
var dsq = function(a,b) {
var dx = a[0]-b[0], dy = a[1]-b[1];
return dx*dx+dy*dy;
},
asq = alpha*alpha,
sites2 =
d3.hexbin().radius(3)(sites)
.map(d => [d.x + 0.01 * (Math.random() - Math.random()), d.y + 0.01 * (Math.random() - Math.random())])
,
mesh = d3.voronoi()
.triangles(sites2)
.filter(function(t) {
return dsq(t[0],t[1]) < asq && dsq(t[0],t[2]) < asq && dsq(t[1],t[2]) < asq;
});
//mesh = mesh.map(d => d.map(e => e.map((Math.round))))
return boundary(mesh);
}
function encircle_path(points) {
var a = alphashape(points, 60);
return a.map(d => d ? "M" + d.join(',') : null)
}
var width = 960,
size = 230,
padding = 20;
var x = d3.scaleLinear()
.range([padding / 2, size - padding / 2]);
var y = d3.scaleLinear()
.range([size - padding / 2, padding / 2]);
var xAxis = d3.axisBottom()
.scale(x)
.ticks(6);
var yAxis = d3.axisLeft()
.scale(y)
.ticks(6);
var color = d3.scaleOrdinal(d3.schemeCategory10);
d3.csv("flowers.csv", function(error, data) {
if (error) throw error;
var domainByTrait = {},
traits = d3.keys(data[0]).filter(function(d) { return d !== "species"; }),
n = traits.length;
traits.forEach(function(trait) {
domainByTrait[trait] = d3.extent(data, function(d) { return d[trait]; });
});
xAxis.tickSize(size * n);
yAxis.tickSize(-size * n);
var brush = d3.brush()
.on("start", brushstart)
.on("brush", brushmove)
.on("end", brushend)
.extent([[0,0],[size,size]]);
var svg = d3.select("body").append("svg")
.attr("width", size * n + padding)
.attr("height", size * n + padding)
.append("g")
.attr("transform", "translate(" + padding + "," + padding / 2 + ")");
svg.selectAll(".x.axis")
.data(traits)
.enter().append("g")
.attr("class", "x axis")
.attr("transform", function(d, i) { return "translate(" + (n - i - 1) * size + ",0)"; })
.each(function(d) { x.domain(domainByTrait[d]); d3.select(this).call(xAxis); });
svg.selectAll(".y.axis")
.data(traits)
.enter().append("g")
.attr("class", "y axis")
.attr("transform", function(d, i) { return "translate(0," + i * size + ")"; })
.each(function(d) { y.domain(domainByTrait[d]); d3.select(this).call(yAxis); });
var cell = svg.selectAll(".cell")
.data(cross(traits, traits))
.enter().append("g")
.attr("class", "cell")
.attr("transform", function(d) { return "translate(" + (n - d.i - 1) * size + "," + d.j * size + ")"; })
.each(plot);
// Titles for the diagonal.
cell.filter(function(d) { return d.i === d.j; }).append("text")
.attr("x", padding)
.attr("y", padding)
.attr("dy", ".71em")
.text(function(d) { return d.x; });
cell.call(brush);
function plot(p) {
var cell = d3.select(this);
x.domain(domainByTrait[p.x]);
y.domain(domainByTrait[p.y]);
cell.append("rect")
.attr("class", "frame")
.attr("x", padding / 2)
.attr("y", padding / 2)
.attr("width", size - padding)
.attr("height", size - padding);
cell.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cx", function(d) { return x(d[p.x]); })
.attr("cy", function(d) { return y(d[p.y]); })
.attr("r", 4)
.style("fill", function(d) { return color(d.species); });
var contours = d3.nest().key(d => d.species).entries(data)
.map(d => {
d.path = encircle_path(d.values.map(d => [x(d[p.x]) + Math.random(), y(d[p.y])]));
return d;
})
cell.selectAll("path.contour")
.data(contours, d => d.key)
.enter()
.append('path')
.classed("contour", true)
.attr('d', d => d.path)
.attr('stroke', d => color(d.key))
.attr('fill', d => color(d.key))
.attr('fill-opacity', 0.3)
}
var brushCell;
// Clear the previously-active brush, if any.
function brushstart(p) {
if (brushCell !== this) {
d3.select(brushCell).call(brush.move, null);
brushCell = this;
x.domain(domainByTrait[p.x]);
y.domain(domainByTrait[p.y]);
}
}
// Highlight the selected circles.
function brushmove(p) {
var e = d3.brushSelection(this);
svg.selectAll("circle").classed("hidden", function(d) {
return !e
? false
: (
e[0][0] > x(+d[p.x]) || x(+d[p.x]) > e[1][0]
|| e[0][1] > y(+d[p.y]) || y(+d[p.y]) > e[1][1]
);
});
var con = cell.selectAll("path.contour")
.data((d,i,e) => {
var c = d3.select(e[i]).selectAll('circle:not(.hidden)');
var p = d3.select(e[i]).data()[0];
x.domain(domainByTrait[p.x]);
y.domain(domainByTrait[p.y]);
return d3.nest()
.key(d => d.species)
.entries(c.data())
.map(d => {
d.path = encircle_path(d.values.map(d => [x(d[p.x]) + Math.random(), y(d[p.y])]));
return d;
})
}, d => d.key)
.attr('d', d => d.path)
x.domain(domainByTrait[p.x]);
y.domain(domainByTrait[p.y]);
con.exit().attr('d', null)
}
// If the brush is empty, select all circles.
function brushend() {
var e = d3.brushSelection(this);
if (e === null) svg.selectAll(".hidden").classed("hidden", false);
}
});
function cross(a, b) {
var c = [], n = a.length, m = b.length, i, j;
for (i = -1; ++i < n;) for (j = -1; ++j < m;) c.push({x: a[i], i: i, y: b[j], j: j});
return c;
}
</script>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-hexbin.v0.2.min.js