ericsoco ericsoco - 4 months ago 46
Javascript Question

How do I apply a scale to a d3 v4.0 `brush`?

In

, I would typically define and set up a brush with code like this:

let brushScale = d3.scaleLinear()
.clamp(true)
.domain([0, 100])
.range([height, 0]);

let brush = d3.brush()
.brushY(brushScale)
.extent([0, 10]);


In
d3 4.x
, I don't see a corresponding function for associating a scale to the brush. Without a scale, I don't understand how I specify the overall range of the brush.

Answer

The meaning of extent has changed from v3 to v4.

extent in v3 meant the brushed area, i.e. the selection range within the overall area circumscribed by the brush.

extent in v4 now refers to the overall area circumscribed by the brush, while the selection is the selected area, what was previously referred to as extent. (Note that the selection can be accessed via d3.brushSelection, but is more commonly accessed as d3.event.selection in a brush event handler.

Also, in d3.v4, scales are no longer associated directly with brushes; instead, a brush operates only over a pixel area. Scales must be applied on the way in (on brush setup) and on the way out (to values returned by brush event handlers). So what was previously, in d3.v3:

let brush = d3.brush() .brushY(brushScale) .extent([0, 10]);

in d3.v4 becomes something like:

let brush = d3.brushY() .extent([[0, brushScale.range()[0]], [sliderWidth, brushScale.range()[1]]]); let brushSel = svg.append('g').call(brush); brush.move(brushSel, [sliderScale(0), sliderScale(10)]);

Note that instead of setting the selected area with extent (v3), we move() (v4) the selected area to a scaled pixel range.

Comments