D3 Scatter with Brush

by ramnathv

HTML

<script src="https://rawgithub.com/square/crossfilter/master/crossfilter.min.js"></script>
<div>
  <a href="#" id="brush-clear" style='visibility: hidden;'>Clear Brush</a>
</div>

CSS

.axis path,
.axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
}

.brush {
    fill: #ccc;
    stroke: #ccc;
    fill-opacity: 0.2;
    stroke-opacity: 0.8;
}

JavaScript

var r = function() { return Math.random(); };

var data = d3.range(20).map(function(d, i){
    return {x: r(), y: r(), c: i % 3, id: i}
})

console.log(data)

var width = 400,
    height = 150,
    margin = 50;

var xScale = d3.scale.linear()
    .range([0, width])
    .nice()


var yScale = d3.scale.linear()
    .range([height, 0])
    .nice()

var xAxis = d3.svg.axis()
    .scale(xScale)
    .ticks(5)
    .orient('bottom');

var yAxis = d3.svg.axis()
    .scale(yScale)
    .ticks(5)
    .orient('left');

var brush = d3.svg.brush()
    .x(xScale)
    .y(yScale);

var svg = d3.select('body')
    .selectAll("svg").data(['a', 'b']).enter().append('svg')
    .attr('class', function(d){return d})
    .attr('width', width+2*margin)
    .attr('height', height+2*margin)
    .append('g')
    .attr('transform', 'translate('+margin+','+margin+')');

svg.append('g')
    .attr('class', 'x axis')
    .attr('transform', 'translate(0,'+height+')')
    .call(xAxis);

svg.append('g')
    .attr('class', 'y axis')
    .call(yAxis);

d3.select("svg.a g").append('g')
    .attr('class', 'brush')
    .call(brush);

var xf = crossfilter(data);
var xDim = xf.dimension(function(d) { return d.x; });
var yDim = xf.dimension(function(d) { return d.y; });

brush.on('brushend', function() {
    var extent = brush.extent(),
        xExtent = [extent[0][0], extent[1][0]],
        yExtent = [extent[0][1], extent[1][1]];
    xDim.filterRange(xExtent);
    yDim.filterRange(yExtent);
    updateDotsB(xExtent, yExtent, false);
    d3.select('#brush-clear').style('visibility', 'visible')
});

xScale1 = xScale.copy()
yScale1 = yScale.copy()

d3.select("#brush-clear").on("click", function(d, i){
  d3.selectAll('.brush').call(brush.clear())
  updateDotsB(0, 0, true)
  d3.select('#brush-clear').style('visibility', 'hidden')
})


function updateDotsB(xExtent, yExtent, reset) {
    if (reset){
       xDim.filterAll()
       yDim.filterAll()
       console.log(xDim.top(Infinity).length)
      ...