Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 13:58
Show Gist options
  • Save Sumbera/9972460 to your computer and use it in GitHub Desktop.
Save Sumbera/9972460 to your computer and use it in GitHub Desktop.
Another brushing with d3

Modified version of Quadtree sample from This version uses Enter,Exit, Update pattern for selecting small portions of larger dataset (here 100T points) with quadtree filtering. This speed up rendering as only relatively small amount of points (given small brush) has to be rendered. This might be useful for maps zooming into details and panning/moving there. Another sources looked at

Move around the brush to discover generated points.

<!DOCTYPE html>
<meta charset="utf-8">
<title>Quadtree 2</title>
.point {
fill: #999;
stroke: #fff;
pointer-events: none;
.brush .extent {
stroke: #fff;
fill-opacity: .125;
shape-rendering: crispEdges;
<script src=""></script>
var width = 1800,
height =1800;
var data = d3.range(100000).map(function (i) {
return {
id : i,
coord: [Math.random() * width, Math.random() * width]
var quadtree = d3.geom.quadtree(
function (v, i) {
return {
x: v.coord[0],
y: v.coord[1],
all: v
var brush = d3.svg.brush()
.x(d3.scale.identity().domain([0, width]))
.y(d3.scale.identity().domain([0, height]))
.extent([[100, 100], [200, 200]])
.on("brush", brushed);
var svg ="body").append("svg")
.attr("width", width)
.attr("height", height);
.attr("class", "brush")
function brushed() {
var extent = brush.extent();
var subset = search(quadtree, extent[0][0], extent[0][1], extent[1][0], extent[1][1]);
var points = svg.selectAll(".point")
.data(subset, function (d) { return; });
.attr("class", "point")
.attr("cx", function (d) { return d.coord[0]; })
.attr("cy", function (d) { return d.coord[1]; })
.attr("r", 4);
// Find the nodes within the specified rectangle.
function search(quadtree, x0, y0, x3, y3) {
var pts = [];
quadtree.visit(function (node, x1, y1, x2, y2) {
var p = node.point;
if ((p) && (p.x >= x0) && (p.x < x3) && (p.y >= y0) && (p.y < y3)) {
return x1 >= x3 || y1 >= y3 || x2 < x0 || y2 < y0;
return pts;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment