• Stars
    star
    487
  • Rank 90,352 (Top 2 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created over 7 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

Compute contour polygons using marching squares.

d3-contour

This library computes contour polygons by applying marching squares to a rectangular array of numeric values. For example, here is Maungawhau’s topology (the classic volcano dataset and terrain.colors from R):

Volcano Contours

For each threshold value, the contour generator constructs a GeoJSON MultiPolygon geometry object representing the area where the input values are greater than or equal to the threshold value. The geometry is in planar coordinates, where ⟨i + 0.5, j + 0.5⟩ corresponds to element i + jn in the input values array. Here is an example that loads a GeoTIFF of surface temperatures, and another that blurs a noisy monochrome PNG to produce smooth contours of cloud fraction:

GeoTiff Contours Cloud Contours

Since the contour polygons are GeoJSON, you can transform and display them using standard tools; see d3.geoPath, d3.geoProject and d3.geoStitch, for example. Here the above contours of surface temperature are displayed in the Natural Earth projection:

GeoTiff Contours II

Contour plots can also visualize continuous functions by sampling. Here is the Goldstein–Price function (a test function for global optimization) and a trippy animation of sin(x + y)sin(x - y):

Contours Animated Contours

Contours can also show the estimated density of point clouds, which is especially useful to avoid overplotting in large datasets. This library implements fast two-dimensional kernel density estimation; see d3.contourDensity. Here is a scatterplot showing the relationship between the idle duration and eruption duration for Old Faithful:

Density Contours

And here is a density contour plot showing the relationship between the weight and price of 53,940 diamonds:

Density Contours

Installing

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

<script type="module">

import {contours} from "https://cdn.jsdelivr.net/npm/d3-contour@4/+esm";

const c = contours(values);

</script>

For legacy environments, you can load d3-contour’s UMD bundle; a d3 global is exported:

<script src="https://cdn.jsdelivr.net/npm/d3-array@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-contour@4"></script>
<script>

// Populate a grid of n×m values where -2 ≤ x ≤ 2 and -2 ≤ y ≤ 1.
const n = 256, m = 256, values = new Array(n * m);
for (let j = 0.5, k = 0; j < m; ++j) {
  for (let i = 0.5; i < n; ++i, ++k) {
    values[k] = goldsteinPrice(i / n * 4 - 2, 1 - j / m * 3);
  }
}

// Compute the contour polygons at log-spaced intervals; returns an array of MultiPolygon.
const contours = d3.contours()
    .size([n, m])
    .thresholds(Array.from({ length: 19 }, (_, i) => Math.pow(2, i + 2)))
    (values);

// See https://en.wikipedia.org/wiki/Test_functions_for_optimization
function goldsteinPrice(x, y) {
  return (1 + Math.pow(x + y + 1, 2) * (19 - 14 * x + 3 * x * x - 14 * y + 6 * x * x + 3 * y * y))
      * (30 + Math.pow(2 * x - 3 * y, 2) * (18 - 32 * x + 12 * x * x + 48 * y - 36 * x * y + 27 * y * y));
}

</script>

API Reference

# d3.contours() · Source, Examples

Constructs a new contour generator with the default settings.

# contours(values) · Source

Computes the contours for the given array of values, returning an array of GeoJSON MultiPolygon geometry objects. Each geometry object represents the area where the input values are greater than or equal to the corresponding threshold value; the threshold value for each geometry object is exposed as geometry.value.

The input values must be an array of length n×m where [n, m] is the contour generator’s size; furthermore, each values[i + jn] must represent the value at the position ⟨i, j⟩. For example, to construct a 256×256 grid for the Goldstein–Price function where -2 ≤ x ≤ 2 and -2 ≤ y ≤ 1:

var n = 256, m = 256, values = new Array(n * m);
for (var j = 0.5, k = 0; j < m; ++j) {
  for (var i = 0.5; i < n; ++i, ++k) {
    values[k] = goldsteinPrice(i / n * 4 - 2, 1 - j / m * 3);
  }
}

function goldsteinPrice(x, y) {
  return (1 + Math.pow(x + y + 1, 2) * (19 - 14 * x + 3 * x * x - 14 * y + 6 * x * x + 3 * y * y))
      * (30 + Math.pow(2 * x - 3 * y, 2) * (18 - 32 * x + 12 * x * x + 48 * y - 36 * x * y + 27 * y * y));
}

The returned geometry objects are typically passed to d3.geoPath to display, using null or d3.geoIdentity as the associated projection.

# contours.contour(values, threshold) · Source, Examples

Computes a single contour, returning a GeoJSON MultiPolygon geometry object representing the area where the input values are greater than or equal to the given threshold value; the threshold value for each geometry object is exposed as geometry.value.

The input values must be an array of length n×m where [n, m] is the contour generator’s size; furthermore, each values[i + jn] must represent the value at the position ⟨i, j⟩. See contours for an example.

# contours.size([size]) · Source, Examples

If size is specified, sets the expected size of the input values grid to the contour generator and returns the contour generator. The size is specified as an array [n, m] where n is the number of columns in the grid and m is the number of rows; n and m must be positive integers. If size is not specified, returns the current size which defaults to [1, 1].

# contours.smooth([smooth]) · Source, Examples

If smooth is specified, sets whether or not the generated contour polygons are smoothed using linear interpolation. If smooth is not specified, returns the current smoothing flag, which defaults to true.

# contours.thresholds([thresholds]) · Source, Examples

If thresholds is specified, sets the threshold generator to the specified function or array and returns this contour generator. If thresholds is not specified, returns the current threshold generator, which by default implements Sturges’ formula.

Thresholds are defined as an array of values [x0, x1, …]. The first generated contour corresponds to the area where the input values are greater than or equal to x0; the second contour corresponds to the area where the input values are greater than or equal to x1, and so on. Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; the threshold value is exposed as geometry.value.

If a count is specified instead of an array of thresholds, then the input values’ extent will be uniformly divided into approximately count bins; see d3.ticks.

Density Estimation

# d3.contourDensity() · Source, Examples

Constructs a new density estimator with the default settings.

# density(data) · Source

Estimates the density contours for the given array of data, returning an array of GeoJSON MultiPolygon geometry objects. Each geometry object represents the area where the estimated number of points per square pixel is greater than or equal to the corresponding threshold value; the threshold value for each geometry object is exposed as geometry.value. The returned geometry objects are typically passed to d3.geoPath to display, using null or d3.geoIdentity as the associated projection. See also d3.contours.

The x- and y-coordinate for each data point are computed using density.x and density.y. In addition, density.weight indicates the relative contribution of each data point (default 1). The generated contours are only accurate within the estimator’s defined size.

# density.x([x]) · Source, Examples

If x is specified, sets the x-coordinate accessor. If x is not specified, returns the current x-coordinate accessor, which defaults to:

function x(d) {
  return d[0];
}

# density.y([y]) · Source, Examples

If y is specified, sets the y-coordinate accessor. If y is not specified, returns the current y-coordinate accessor, which defaults to:

function y(d) {
  return d[1];
}

# density.weight([weight]) · Source

If weight is specified, sets the accessor for point weights. If weight is not specified, returns the current point weight accessor, which defaults to:

function weight() {
  return 1;
}

# density.size([size]) · Source, Examples

If size is specified, sets the size of the density estimator to the specified bounds and returns the estimator. The size is specified as an array [width, height], where width is the maximum x-value and height is the maximum y-value. If size is not specified, returns the current size which defaults to [960, 500]. The estimated density contours are only accurate within the defined size.

# density.cellSize([cellSize]) · Source

If cellSize is specified, sets the size of individual cells in the underlying bin grid to the specified positive integer and returns the estimator. If cellSize is not specified, returns the current cell size, which defaults to 4. The cell size is rounded down to the nearest power of two. Smaller cells produce more detailed contour polygons, but are more expensive to compute.

# density.thresholds([thresholds]) · Source, Examples

If thresholds is specified, sets the threshold generator to the specified function or array and returns this contour generator. If thresholds is not specified, returns the current threshold generator, which by default generates about twenty nicely-rounded density thresholds.

Thresholds are defined as an array of values [x0, x1, …]. The first generated density contour corresponds to the area where the estimated density is greater than or equal to x0; the second contour corresponds to the area where the estimated density is greater than or equal to x1, and so on. Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; the threshold value is exposed as geometry.value. The first value x0 should typically be greater than zero.

If a count is specified instead of an array of thresholds, then approximately count uniformly-spaced nicely-rounded thresholds will be generated; see d3.ticks.

# density.bandwidth([bandwidth]) · Source, Examples

If bandwidth is specified, sets the bandwidth (the standard deviation) of the Gaussian kernel and returns the estimate. If bandwidth is not specified, returns the current bandwidth, which defaults to 20.4939…. The specified bandwidth is currently rounded to the nearest supported value by this implementation, and must be nonnegative.

# density.contours(data) · Source, Examples

Return a contour(value) function that can be used to compute an arbitrary contour on the given data without needing to recompute the underlying grid. The returned contour function also exposes a contour.max value which represents the maximum density of the grid.

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-interpolate

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

d3-array

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

d3-dsv

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

d3-color

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

d3-drag

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

d3-time-format

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

d3-voronoi

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

d3-hexbin

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

d3-time

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

d3-quadtree

Two-dimensional recursive spatial subdivision.
JavaScript
225
star
27

d3-transition

Animated transitions for D3 selections.
JavaScript
219
star
28

d3-fetch

Convenient parsing for Fetch.
JavaScript
215
star
29

d3-axis

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

d3.github.com

The D3 website.
JavaScript
195
star
31

d3-path

Serialize Canvas path commands to SVG.
JavaScript
192
star
32

d3-timer

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

d3-brush

Select a one- or two-dimensional region using the mouse or touch.
JavaScript
154
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