• Stars
    star
    154
  • Rank 242,095 (Top 5 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created over 8 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Select a one- or two-dimensional region using the mouse or touch.

d3-brush

Brushing is the interactive specification a one- or two-dimensional selected region using a pointing gesture, such as by clicking and dragging the mouse. Brushing is often used to select discrete elements, such as dots in a scatterplot or files on a desktop. It can also be used to zoom-in to a region of interest, or to select continuous regions for cross-filtering data or live histograms:

Mona Lisa Histogram

The d3-brush module implements brushing for mouse and touch events using SVG. Click and drag on the brush selection to translate the selection. Click and drag on one of the selection handles to move the corresponding edge (or edges) of the selection. Click and drag on the invisible overlay to define a new brush selection, or click anywhere within the brushable region while holding down the META (⌘) key. Holding down the ALT (⌥) key while moving the brush causes it to reposition around its center, while holding down SPACE locks the current brush size, allowing only translation.

Brushes also support programmatic control. For example, you can listen to end events, and then initiate a transition with brush.move to snap the brush selection to semantic boundaries:

Brush Snapping

Or you can have the brush recenter when you click outside the current selection:

Click-to-Recenter

Installing

If you use npm, npm install d3-brush. You can also download the latest release on GitHub. For vanilla HTML in modern browsers, import d3-brush from Skypack:

<script type="module">

import {brushX} from "https://cdn.skypack.dev/d3-brush@3";

const brush = brushX();

</script>

For legacy environments, you can load d3-brush’s UMD bundle from an npm-based CDN such as jsDelivr; a d3 global is exported:

<script src="https://cdn.jsdelivr.net/npm/d3-color@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-dispatch@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-ease@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-interpolate@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-selection@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-timer@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-drag@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-transition@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-brush@3"></script>
<script>

const brush = d3.brushX();

</script>

Try d3-brush in your browser.

API Reference

# d3.brush() · Source, Examples

Creates a new two-dimensional brush.

# d3.brushX() · Source, Examples

Creates a new one-dimensional brush along the x-dimension.

# d3.brushY() · Source

Creates a new one-dimensional brush along the y-dimension.

# brush(group) · Source, Examples

Applies the brush to the specified group, which must be a selection of SVG G elements. This function is typically not invoked directly, and is instead invoked via selection.call. For example, to render a brush:

svg.append("g")
    .attr("class", "brush")
    .call(d3.brush().on("brush", brushed));

Internally, the brush uses selection.on to bind the necessary event listeners for dragging. The listeners use the name .brush, so you can subsequently unbind the brush event listeners as follows:

group.on(".brush", null);

The brush also creates the SVG elements necessary to display the brush selection and to receive input events for interaction. You can add, remove or modify these elements as desired to change the brush appearance; you can also apply stylesheets to modify the brush appearance. The structure of a two-dimensional brush is as follows:

<g class="brush" fill="none" pointer-events="all" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
  <rect class="overlay" pointer-events="all" cursor="crosshair" x="0" y="0" width="960" height="500"></rect>
  <rect class="selection" cursor="move" fill="#777" fill-opacity="0.3" stroke="#fff" shape-rendering="crispEdges" x="112" y="194" width="182" height="83"></rect>
  <rect class="handle handle--n" cursor="ns-resize" x="107" y="189" width="192" height="10"></rect>
  <rect class="handle handle--e" cursor="ew-resize" x="289" y="189" width="10" height="93"></rect>
  <rect class="handle handle--s" cursor="ns-resize" x="107" y="272" width="192" height="10"></rect>
  <rect class="handle handle--w" cursor="ew-resize" x="107" y="189" width="10" height="93"></rect>
  <rect class="handle handle--nw" cursor="nwse-resize" x="107" y="189" width="10" height="10"></rect>
  <rect class="handle handle--ne" cursor="nesw-resize" x="289" y="189" width="10" height="10"></rect>
  <rect class="handle handle--se" cursor="nwse-resize" x="289" y="272" width="10" height="10"></rect>
  <rect class="handle handle--sw" cursor="nesw-resize" x="107" y="272" width="10" height="10"></rect>
</g>

The overlay rect covers the brushable area defined by brush.extent. The selection rect covers the area defined by the current brush selection. The handle rects cover the edges and corners of the brush selection, allowing the corresponding value in the brush selection to be modified interactively. To modify the brush selection programmatically, use brush.move.

# brush.move(group, selection[, event]) · Source, Examples

Sets the active selection of the brush on the specified group, which must be a selection or a transition of SVG G elements. The selection must be defined as an array of numbers, or null to clear the brush selection. For a two-dimensional brush, it must be defined as [[x0, y0], [x1, y1]], where x0 is the minimum x-value, y0 is the minimum y-value, x1 is the maximum x-value, and y1 is the maximum y-value. For an x-brush, it must be defined as [x0, x1]; for a y-brush, it must be defined as [y0, y1]. The selection may also be specified as a function which returns such an array; if a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. The returned array defines the brush selection for that element.

# brush.clear(group[, event]) · Source, Examples

An alias for brush.move with the null selection.

# brush.extent([extent]) · Source, Examples

If extent is specified, sets the brushable extent to the specified array of points [[x0, y0], [x1, y1]], where [x0, y0] is the top-left corner and [x1, y1] is the bottom-right corner, and returns this brush. The extent may also be specified as a function which returns such an array; if a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. If extent is not specified, returns the current extent accessor, which defaults to:

function defaultExtent() {
  var svg = this.ownerSVGElement || this;
  if (svg.hasAttribute("viewBox")) {
    svg = svg.viewBox.baseVal;
    return [[svg.x, svg.y], [svg.x + svg.width, svg.y + svg.height]];
  }
  return [[0, 0], [svg.width.baseVal.value, svg.height.baseVal.value]];
}

This default implementation requires that the owner SVG element have a defined viewBox, or width and height attributes. Alternatively, consider using element.getBoundingClientRect. (In Firefox, element.clientWidth and element.clientHeight is zero for SVG elements!)

The brush extent determines the size of the invisible overlay and also constrains the brush selection; the brush selection cannot go outside the brush extent.

# brush.filter([filter]) · Source, Examples

If filter is specified, sets the filter to the specified function and returns the brush. If filter is not specified, returns the current filter, which defaults to:

function filter(event) {
  return !event.ctrlKey && !event.button;
}

If the filter returns falsey, the initiating event is ignored and no brush gesture is started. Thus, the filter determines which input events are ignored. The default filter ignores mousedown events on secondary buttons, since those buttons are typically intended for other purposes, such as the context menu.

# brush.touchable([touchable]) · Source

If touchable is specified, sets the touch support detector to the specified function and returns the brush. If touchable is not specified, returns the current touch support detector, which defaults to:

function touchable() {
  return navigator.maxTouchPoints || ("ontouchstart" in this);
}

Touch event listeners are only registered if the detector returns truthy for the corresponding element when the brush is applied. The default detector works well for most browsers that are capable of touch input, but not all; Chrome’s mobile device emulator, for example, fails detection.

# brush.keyModifiers([modifiers]) · Source

If modifiers is specified, sets whether the brush listens to key events during brushing and returns the brush. If modifiers is not specified, returns the current behavior, which defaults to true.

# brush.handleSize([size]) · Source

If size is specified, sets the size of the brush handles to the specified number and returns the brush. If size is not specified, returns the current handle size, which defaults to six. This method must be called before applying the brush to a selection; changing the handle size does not affect brushes that were previously rendered.

# brush.on(typenames[, listener]) · Source

If listener is specified, sets the event listener for the specified typenames and returns the brush. If an event listener was already registered for the same type and name, the existing listener is removed before the new listener is added. If listener is null, removes the current event listeners for the specified typenames, if any. If listener is not specified, returns the first currently-assigned listener matching the specified typenames, if any. When a specified event is dispatched, each listener will be invoked with the same context and arguments as selection.on listeners: the current event event and datum d, with the this context as the current DOM element.

The typenames is a string containing one or more typename separated by whitespace. Each typename is a type, optionally followed by a period (.) and a name, such as brush.foo and brush.bar; the name allows multiple listeners to be registered for the same type. The type must be one of the following:

  • start - at the start of a brush gesture, such as on mousedown.
  • brush - when the brush moves, such as on mousemove.
  • end - at the end of a brush gesture, such as on mouseup.

See dispatch.on and Brush Events for more.

# d3.brushSelection(node) · Source, Examples

Returns the current brush selection for the specified node. Internally, an element’s brush state is stored as element.__brush; however, you should use this method rather than accessing it directly. If the given node has no selection, returns null. Otherwise, the selection is defined as an array of numbers. For a two-dimensional brush, it is [[x0, y0], [x1, y1]], where x0 is the minimum x-value, y0 is the minimum y-value, x1 is the maximum x-value, and y1 is the maximum y-value. For an x-brush, it is [x0, x1]; for a y-brush, it is [y0, y1].

Brush Events

When a brush event listener is invoked, it receives the current brush event. The event object exposes several fields:

  • target - the associated brush behavior.
  • type - the string “start”, “brush” or “end”; see brush.on.
  • selection - the current brush selection.
  • sourceEvent - the underlying input event, such as mousemove or touchmove.
  • mode - the string “drag”, “space”, “handle” or “center”; the mode of the brush.

More Repositories

1

d3

Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript
106,311
star
2

d3-shape

Graphical primitives for visualization, such as lines and areas.
JavaScript
2,458
star
3

d3-plugins

[DEPRECATED] A repository for sharing D3.js V3 plugins.
JavaScript
1,808
star
4

d3-force

Force-directed graph layout using velocity Verlet integration.
JavaScript
1,702
star
5

d3-scale

Encodings that map abstract data to visual representation.
JavaScript
1,567
star
6

d3-queue

Evaluate asynchronous tasks with configurable concurrency.
JavaScript
1,411
star
7

d3-hierarchy

2D layout algorithms for visualizing hierarchical data.
JavaScript
1,064
star
8

d3-geo-projection

Extended geographic projections for d3-geo.
JavaScript
1,058
star
9

d3-geo

Geographic projections, spherical shapes and spherical trigonometry.
JavaScript
988
star
10

d3-scale-chromatic

Sequential, diverging and categorical color scales.
JavaScript
787
star
11

d3-sankey

Visualize flow between nodes in a directed acyclic network.
JavaScript
763
star
12

d3-format

Format numbers for human consumption.
JavaScript
611
star
13

d3-delaunay

Compute the Voronoi diagram of a set of two-dimensional points.
JavaScript
606
star
14

d3-ease

Easing functions for smooth animation.
JavaScript
604
star
15

d3-selection

Transform the DOM by selecting elements and joining to data.
JavaScript
547
star
16

d3-zoom

Pan and zoom SVG, HTML or Canvas using mouse or touch input.
JavaScript
495
star
17

d3-contour

Compute contour polygons using marching squares.
JavaScript
487
star
18

d3-interpolate

Interpolate numbers, colors, strings, arrays, objects, whatever!
JavaScript
482
star
19

d3-array

Array manipulation, ordering, searching, summarizing, etc.
JavaScript
452
star
20

d3-dsv

A parser and formatter for delimiter-separated values, such as CSV and TSV.
JavaScript
416
star
21

d3-color

Color spaces! RGB, HSL, Cubehelix, CIELAB, and more.
JavaScript
389
star
22

d3-drag

Drag and drop SVG, HTML or Canvas using mouse or touch input.
JavaScript
328
star
23

d3-time-format

Parse and format times, inspired by strptime and strftime.
JavaScript
324
star
24

d3-voronoi

Compute the Voronoi diagram of a set of two-dimensional points.
JavaScript
250
star
25

d3-hexbin

Group two-dimensional points into hexagonal bins.
JavaScript
231
star
26

d3-time

A calculator for humanity’s peculiar conventions of time.
JavaScript
227
star
27

d3-quadtree

Two-dimensional recursive spatial subdivision.
JavaScript
225
star
28

d3-transition

Animated transitions for D3 selections.
JavaScript
219
star
29

d3-fetch

Convenient parsing for Fetch.
JavaScript
215
star
30

d3-axis

Human-readable reference marks for scales.
JavaScript
204
star
31

d3.github.com

The D3 website.
JavaScript
195
star
32

d3-path

Serialize Canvas path commands to SVG.
JavaScript
192
star
33

d3-timer

An efficient queue for managing thousands of concurrent animations.
JavaScript
159
star
34

d3-3.x-api-reference

An archive of the D3 3.x API Reference.
153
star
35

d3-random

Generate random numbers from various distributions.
JavaScript
136
star
36

d3-chord

Visualizations relationships or network flow with a circular layout.
JavaScript
122
star
37

d3-tile

Compute the quadtree tiles to display in a rectangular viewport.
JavaScript
120
star
38

d3-collection

Handy data structures for elements keyed by string.
JavaScript
111
star
39

d3-request

A convenient alternative to XMLHttpRequest.
JavaScript
109
star
40

d3-geo-polygon

Clipping and geometric operations for spherical polygons.
JavaScript
102
star
41

d3-polygon

Geometric operations for two-dimensional polygons.
JavaScript
97
star
42

d3-require

A minimal, promise-based implementation to require asynchronous module definitions.
JavaScript
79
star
43

d3-selection-multi

Multi-value syntax for d3-selection and d3-transition.
JavaScript
75
star
44

d3-dispatch

Register named callbacks and call them with arguments.
JavaScript
75
star
45

versor

a home for Mike Bostock's versor.js
JavaScript
34
star
46

d3-bundler

DEPRECATED; use rollup/rollup.
JavaScript
34
star
47

d3-hsv

The HSV (Hue, Saturation, Value) color space.
JavaScript
26
star
48

d3-logo

D3 brand assets.
23
star
49

d3-cam16

A d3 implementation of the CIECAM16 color appearance model.
JavaScript
22
star
50

d3-hcg

The HCG (Hue, Chroma, Grayness) color space derived from the Munsell color system.
JavaScript
20
star
51

d3-scripts

Common scripts for D3 modules.
JavaScript
15
star
52

d3-hull

DEPRECATED; see d3-polygon’s hull function.
JavaScript
14
star
53

blur-benchmark

temporary benchmark for d3.blur implementations
JavaScript
2
star