# https://d3js.org/api llms-full.txt

## D3.js API Documentation
[Skip to content](https://d3js.org/api#VPContent)

On this page

# API index [​](https://d3js.org/api\#api-index)

D3 is a collection of modules that are designed to work together; you can use the modules independently, or you can use them together as part of the default build.

## [d3-array](https://d3js.org/d3-array) [​](https://d3js.org/api\#d3-array)

Array manipulation, ordering, searching, summarizing, _etc._

### [Add](https://d3js.org/d3-array/add) [​](https://d3js.org/api\#add)

Add floating point values with full precision.

- [new Adder](https://d3js.org/d3-array/add#Adder) \- create a full precision adder.
- [_adder_.add](https://d3js.org/d3-array/add#adder_add) \- add a value to an adder.
- [_adder_.valueOf](https://d3js.org/d3-array/add#adder_valueOf) \- get the double-precision representation of an adder’s value.
- [fcumsum](https://d3js.org/d3-array/add#fcumsum) \- compute a full precision cumulative summation of numbers.
- [fsum](https://d3js.org/d3-array/add#fsum) \- compute a full precision summation of an iterable of numbers.

### [Bin](https://d3js.org/d3-array/bin) [​](https://d3js.org/api\#bin)

Bin discrete samples into continuous, non-overlapping intervals.

- [bin](https://d3js.org/d3-array/bin#bin) \- create a new bin generator.
- [_bin_](https://d3js.org/d3-array/bin#_bin) \- bins a given array of samples.
- [_bin_.value](https://d3js.org/d3-array/bin#bin_value) \- specify a value accessor for each sample.
- [_bin_.domain](https://d3js.org/d3-array/bin#bin_domain) \- specify the interval of observable values.
- [_bin_.thresholds](https://d3js.org/d3-array/bin#bin_thresholds) \- specify how values are divided into bins.
- [thresholdFreedmanDiaconis](https://d3js.org/d3-array/bin#thresholdFreedmanDiaconis) \- the Freedman–Diaconis binning rule.
- [thresholdScott](https://d3js.org/d3-array/bin#thresholdScott) \- Scott’s normal reference binning rule.
- [thresholdSturges](https://d3js.org/d3-array/bin#thresholdSturges) \- Sturges’ binning formula.

### [Bisect](https://d3js.org/d3-array/bisect) [​](https://d3js.org/api\#bisect)

Quickly find a value in a sorted array.

- [bisector](https://d3js.org/d3-array/bisect#bisector) \- bisect using an accessor or comparator.
- [_bisector_.right](https://d3js.org/d3-array/bisect#bisector_right) \- bisectRight, with the given comparator.
- [_bisector_.left](https://d3js.org/d3-array/bisect#bisector_left) \- bisectLeft, with the given comparator.
- [_bisector_.center](https://d3js.org/d3-array/bisect#bisector_center) \- binary search for a value in a sorted array.
- [bisect](https://d3js.org/d3-array/bisect#bisect) \- binary search for a value in a sorted array.
- [bisectRight](https://d3js.org/d3-array/bisect#bisectRight) \- binary search for a value in a sorted array.
- [bisectLeft](https://d3js.org/d3-array/bisect#bisectLeft) \- binary search for a value in a sorted array.
- [bisectCenter](https://d3js.org/d3-array/bisect#bisectCenter) \- binary search for a value in a sorted array.

### [Blur](https://d3js.org/d3-array/blur) [​](https://d3js.org/api\#blur)

Blur quantitative values in one or two dimensions.

- [d3.blur](https://d3js.org/d3-array/blur#blur) \- blur an array of numbers in place.
- [d3.blur2](https://d3js.org/d3-array/blur#blur2) \- blur a two-dimensional array of numbers in place.
- [d3.blurImage](https://d3js.org/d3-array/blur#blurImage) \- blur an RGBA ImageData in place.

### [Group](https://d3js.org/d3-array/group) [​](https://d3js.org/api\#group)

Group discrete values.

- [d3.group](https://d3js.org/d3-array/group#group) \- group an iterable into a nested Map.
- [d3.groups](https://d3js.org/d3-array/group#groups) \- group an iterable into a nested array.
- [d3.rollup](https://d3js.org/d3-array/group#rollup) \- reduce an iterable into a nested Map.
- [d3.rollups](https://d3js.org/d3-array/group#rollups) \- reduce an iterable into a nested array.
- [d3.index](https://d3js.org/d3-array/group#index) \- index an iterable into a nested Map.
- [d3.indexes](https://d3js.org/d3-array/group#indexes) \- index an iterable into a nested array.
- [d3.flatGroup](https://d3js.org/d3-array/group#flatGroup) \- group an iterable into a flat array.
- [d3.flatRollup](https://d3js.org/d3-array/group#flatRollup) \- reduce an iterable into a flat array.
- [d3.groupSort](https://d3js.org/d3-array/group#groupSort) \- sort keys according to grouped values.

### [Intern](https://d3js.org/d3-array/intern) [​](https://d3js.org/api\#intern)

Create maps and sets with non-primitive values such as dates.

- [new InternMap](https://d3js.org/d3-array/intern#InternMap) \- a key-interning Map.
- [new InternSet](https://d3js.org/d3-array/intern#InternSet) \- a value-interning Set.

### [Sets](https://d3js.org/d3-array/sets) [​](https://d3js.org/api\#sets)

Logical operations on sets.

- [d3.difference](https://d3js.org/d3-array/sets#difference) \- compute a set difference.
- [d3.disjoint](https://d3js.org/d3-array/sets#disjoint) \- test whether two sets are disjoint.
- [d3.intersection](https://d3js.org/d3-array/sets#intersection) \- compute a set intersection.
- [d3.superset](https://d3js.org/d3-array/sets#superset) \- test whether a set is a superset of another.
- [d3.subset](https://d3js.org/d3-array/sets#subset) \- test whether a set is a subset of another.
- [d3.union](https://d3js.org/d3-array/sets#union) \- compute a set union.

### [Sort](https://d3js.org/d3-array/sort) [​](https://d3js.org/api\#sort)

Sort and reorder arrays of values.

- [d3.ascending](https://d3js.org/d3-array/sort#ascending) \- compute the natural order of two values.
- [d3.descending](https://d3js.org/d3-array/sort#descending) \- compute the natural order of two values.
- [d3.permute](https://d3js.org/d3-array/sort#permute) \- reorder an iterable of elements according to an iterable of indexes.
- [d3.quickselect](https://d3js.org/d3-array/sort#quickselect) \- reorder an array of numbers.
- [d3.reverse](https://d3js.org/d3-array/sort#reverse) \- reverse the order of values.
- [d3.shuffle](https://d3js.org/d3-array/sort#shuffle) \- randomize the order of an iterable.
- [d3.shuffler](https://d3js.org/d3-array/sort#shuffler) \- randomize the order of an iterable.
- [d3.sort](https://d3js.org/d3-array/sort#sort) \- sort values.

### [Summarize](https://d3js.org/d3-array/summarize) [​](https://d3js.org/api\#summarize)

Compute summary statistics.

- [d3.count](https://d3js.org/d3-array/summarize#count) \- count valid number values in an iterable.
- [d3.min](https://d3js.org/d3-array/summarize#min) \- compute the minimum value in an iterable.
- [d3.minIndex](https://d3js.org/d3-array/summarize#minIndex) \- compute the index of the minimum value in an iterable.
- [d3.max](https://d3js.org/d3-array/summarize#max) \- compute the maximum value in an iterable.
- [d3.maxIndex](https://d3js.org/d3-array/summarize#maxIndex) \- compute the index of the maximum value in an iterable.
- [d3.least](https://d3js.org/d3-array/summarize#least) \- returns the least element of an iterable.
- [d3.leastIndex](https://d3js.org/d3-array/summarize#leastIndex) \- returns the index of the least element of an iterable.
- [d3.greatest](https://d3js.org/d3-array/summarize#greatest) \- returns the greatest element of an iterable.
- [d3.greatestIndex](https://d3js.org/d3-array/summarize#greatestIndex) \- returns the index of the greatest element of an iterable.
- [d3.extent](https://d3js.org/d3-array/summarize#extent) \- compute the minimum and maximum value in an iterable.
- [d3.mode](https://d3js.org/d3-array/summarize#mode) \- compute the mode (the most common value) of an iterable of numbers.
- [d3.sum](https://d3js.org/d3-array/summarize#sum) \- compute the sum of an iterable of numbers.
- [d3.mean](https://d3js.org/d3-array/summarize#mean) \- compute the arithmetic mean of an iterable of numbers.
- [d3.median](https://d3js.org/d3-array/summarize#median) \- compute the median of an iterable of numbers (the 0.5-quantile).
- [d3.medianIndex](https://d3js.org/d3-array/summarize#median) \- compute the median index of an iterable of numbers (the 0.5-quantile).
- [d3.cumsum](https://d3js.org/d3-array/summarize#cumsum) \- compute the cumulative sum of an iterable.
- [d3.quantile](https://d3js.org/d3-array/summarize#quantile) \- compute a quantile for an iterable of numbers.
- [d3.quantileIndex](https://d3js.org/d3-array/summarize#quantileIndex) \- compute a quantile index for an iterable of numbers.
- [d3.quantileSorted](https://d3js.org/d3-array/summarize#quantileSorted) \- compute a quantile for a sorted array of numbers.
- [d3.rank](https://d3js.org/d3-array/summarize#rank) \- compute the rank order of an iterable.
- [d3.variance](https://d3js.org/d3-array/summarize#variance) \- compute the variance of an iterable of numbers.
- [d3.deviation](https://d3js.org/d3-array/summarize#deviation) \- compute the standard deviation of an iterable of numbers.
- [d3.every](https://d3js.org/d3-array/summarize#every) \- test if all values satisfy a condition.
- [d3.some](https://d3js.org/d3-array/summarize#some) \- test if any value satisfies a condition.

### [Ticks](https://d3js.org/d3-array/ticks) [​](https://d3js.org/api\#ticks)

Generate representative values from a continuous interval.

- [d3.ticks](https://d3js.org/d3-array/ticks#ticks) \- generate representative values from a numeric interval.
- [d3.tickIncrement](https://d3js.org/d3-array/ticks#tickIncrement) \- generate representative values from a numeric interval.
- [d3.tickStep](https://d3js.org/d3-array/ticks#tickStep) \- generate representative values from a numeric interval.
- [d3.nice](https://d3js.org/d3-array/ticks#nice) \- extend an interval to align with ticks.
- [d3.range](https://d3js.org/d3-array/ticks#range) \- generate a range of numeric values.

### [Transform](https://d3js.org/d3-array/transform) [​](https://d3js.org/api\#transform)

Derive new arrays.

- [d3.cross](https://d3js.org/d3-array/transform#cross) \- compute the Cartesian product of two iterables.
- [d3.merge](https://d3js.org/d3-array/transform#merge) \- merge multiple iterables into one array.
- [d3.pairs](https://d3js.org/d3-array/transform#pairs) \- create an array of adjacent pairs of elements.
- [d3.transpose](https://d3js.org/d3-array/transform#transpose) \- transpose an array of arrays.
- [d3.zip](https://d3js.org/d3-array/transform#zip) \- transpose a variable number of arrays.
- [d3.filter](https://d3js.org/d3-array/transform#filter) \- filter values.
- [d3.map](https://d3js.org/d3-array/transform#map) \- map values.
- [d3.reduce](https://d3js.org/d3-array/transform#reduce) \- reduce values.

## [d3-axis](https://d3js.org/d3-axis) [​](https://d3js.org/api\#d3-axis)

Human-readable reference marks for scales.

- [d3.axisTop](https://d3js.org/d3-axis#axisTop) \- create a new top-oriented axis generator.
- [d3.axisRight](https://d3js.org/d3-axis#axisRight) \- create a new right-oriented axis generator.
- [d3.axisBottom](https://d3js.org/d3-axis#axisBottom) \- create a new bottom-oriented axis generator.
- [d3.axisLeft](https://d3js.org/d3-axis#axisLeft) \- create a new left-oriented axis generator.
- [_axis_](https://d3js.org/d3-axis#_axis) \- generate an axis for the given selection.
- [_axis_.scale](https://d3js.org/d3-axis#axis_scale) \- set the scale.
- [_axis_.ticks](https://d3js.org/d3-axis#axis_ticks) \- customize how ticks are generated and formatted.
- [_axis_.tickArguments](https://d3js.org/d3-axis#axis_tickArguments) \- customize how ticks are generated and formatted.
- [_axis_.tickValues](https://d3js.org/d3-axis#axis_tickValues) \- set the tick values explicitly.
- [_axis_.tickFormat](https://d3js.org/d3-axis#axis_tickFormat) \- set the tick format explicitly.
- [_axis_.tickSize](https://d3js.org/d3-axis#axis_tickSize) \- set the size of the ticks.
- [_axis_.tickSizeInner](https://d3js.org/d3-axis#axis_tickSizeInner) \- set the size of inner ticks.
- [_axis_.tickSizeOuter](https://d3js.org/d3-axis#axis_tickSizeOuter) \- set the size of outer (extent) ticks.
- [_axis_.tickPadding](https://d3js.org/d3-axis#axis_tickPadding) \- set the padding between ticks and labels.
- [_axis_.offset](https://d3js.org/d3-axis#axis_offset) \- set the pixel offset for crisp edges.

## [d3-brush](https://d3js.org/d3-brush) [​](https://d3js.org/api\#d3-brush)

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

- [d3.brush](https://d3js.org/d3-brush#brush) \- create a new two-dimensional brush.
- [d3.brushX](https://d3js.org/d3-brush#brushX) \- create a brush along the _x_-dimension.
- [d3.brushY](https://d3js.org/d3-brush#brushY) \- create a brush along the _y_-dimension.
- [_brush_](https://d3js.org/d3-brush#_brush) \- apply the brush to a selection.
- [_brush_.move](https://d3js.org/d3-brush#brush_move) \- move the brush selection.
- [_brush_.clear](https://d3js.org/d3-brush#brush_clear) \- clear the brush selection.
- [_brush_.extent](https://d3js.org/d3-brush#brush_extent) \- define the brushable region.
- [_brush_.filter](https://d3js.org/d3-brush#brush_filter) \- control which input events initiate brushing.
- [_brush_.touchable](https://d3js.org/d3-brush#brush_touchable) \- set the touch support detector.
- [_brush_.keyModifiers](https://d3js.org/d3-brush#brush_keyModifiers) \- enable or disable key interaction.
- [_brush_.handleSize](https://d3js.org/d3-brush#brush_handleSize) \- set the size of the brush handles.
- [_brush_.on](https://d3js.org/d3-brush#brush_on) \- listen for brush events.
- [d3.brushSelection](https://d3js.org/d3-brush#brushSelection) \- get the brush selection for a given node.

## [d3-chord](https://d3js.org/d3-chord) [​](https://d3js.org/api\#d3-chord)

- [d3.chord](https://d3js.org/d3-chord/chord#chord) \- create a new chord layout.
- [_chord_](https://d3js.org/d3-chord/chord#_chord) \- compute the layout for the given matrix.
- [_chord_.padAngle](https://d3js.org/d3-chord/chord#chord_padAngle) \- set the padding between adjacent groups.
- [_chord_.sortGroups](https://d3js.org/d3-chord/chord#chord_sortGroups) \- define the group order.
- [_chord_.sortSubgroups](https://d3js.org/d3-chord/chord#chord_sortSubgroups) \- define the source and target order within groups.
- [_chord_.sortChords](https://d3js.org/d3-chord/chord#chord_sortChords) \- define the chord order across groups.
- [d3.chordDirected](https://d3js.org/d3-chord/chord#chordDirected) \- create a directed chord generator.
- [d3.chordTranspose](https://d3js.org/d3-chord/chord#chordTranspose) \- create a transposed chord generator.
- [d3.ribbon](https://d3js.org/d3-chord/ribbon#ribbon) \- create a ribbon shape generator.
- [_ribbon_](https://d3js.org/d3-chord/ribbon#_ribbon) \- generate a ribbon shape.
- [_ribbon_.source](https://d3js.org/d3-chord/ribbon#ribbon_source) \- set the source accessor.
- [_ribbon_.target](https://d3js.org/d3-chord/ribbon#ribbon_target) \- set the target accessor.
- [_ribbon_.radius](https://d3js.org/d3-chord/ribbon#ribbon_radius) \- set the ribbon source and target radius.
- [_ribbon_.sourceRadius](https://d3js.org/d3-chord/ribbon#ribbon_sourceRadius) \- set the ribbon source radius.
- [_ribbon_.targetRadius](https://d3js.org/d3-chord/ribbon#ribbon_targetRadius) \- set the ribbon target radius.
- [_ribbon_.startAngle](https://d3js.org/d3-chord/ribbon#ribbon_startAngle) \- set the ribbon source or target start angle.
- [_ribbon_.endAngle](https://d3js.org/d3-chord/ribbon#ribbon_endAngle) \- set the ribbon source or target end angle.
- [_ribbon_.padAngle](https://d3js.org/d3-chord/ribbon#ribbon_padAngle) \- set the pad angle accessor.
- [_ribbon_.context](https://d3js.org/d3-chord/ribbon#ribbon_context) \- set the render context.
- [d3.ribbonArrow](https://d3js.org/d3-chord/ribbon#ribbonArrow) \- create an arrow ribbon generator.
- [_ribbonArrow_.headRadius](https://d3js.org/d3-chord/ribbon#ribbonArrow_headRadius) \- set the arrowhead radius accessor.

## [d3-color](https://d3js.org/d3-color) [​](https://d3js.org/api\#d3-color)

Color manipulation and color space conversion.

- [d3.color](https://d3js.org/d3-color#color) \- parse the given CSS color specifier.
- [_color_.opacity](https://d3js.org/d3-color#color_opacity) \- the color’s opacity.
- [_color_.rgb](https://d3js.org/d3-color#color_rgb) \- compute the RGB equivalent of this color.
- [_color_.copy](https://d3js.org/d3-color#color_copy) \- return a copy of this color.
- [_color_.brighter](https://d3js.org/d3-color#color_brighter) \- create a brighter copy of this color.
- [_color_.darker](https://d3js.org/d3-color#color_darker) \- create a darker copy of this color.
- [_color_.displayable](https://d3js.org/d3-color#color_displayable) \- returns true if the color is displayable on standard hardware.
- [_color_.formatHex](https://d3js.org/d3-color#color_formatHex) \- returns the hexadecimal RRGGBB string representation of this color.
- [_color_.formatHex8](https://d3js.org/d3-color#color_formatHex8) \- returns the hexadecimal RRGGBBAA string representation of this color.
- [_color_.formatHsl](https://d3js.org/d3-color#color_formatHsl) \- returns the RGB string representation of this color.
- [_color_.formatRgb](https://d3js.org/d3-color#color_formatRgb) \- returns the HSL string representation of this color.
- [_color_.toString](https://d3js.org/d3-color#color_toString) \- returns the RGB string representation of this color.
- [d3.rgb](https://d3js.org/d3-color#rgb) \- create a new RGB color.
- [_rgb_.clamp](https://d3js.org/d3-color#rgb_clamp) \- returns copy of this color clamped to the RGB color space.
- [d3.hsl](https://d3js.org/d3-color#hsl) \- create a new HSL color.
- [_hsl_.clamp](https://d3js.org/d3-color#hsl_clamp) \- returns copy of this color clamped to the HSL color space.
- [d3.lab](https://d3js.org/d3-color#lab) \- create a new Lab color.
- [d3.gray](https://d3js.org/d3-color#gray) \- create a new Lab gray.
- [d3.hcl](https://d3js.org/d3-color#hcl) \- create a new HCL color.
- [d3.lch](https://d3js.org/d3-color#lch) \- create a new HCL color.
- [d3.cubehelix](https://d3js.org/d3-color#cubehelix) \- create a new Cubehelix color.

## [d3-contour](https://d3js.org/d3-contour) [​](https://d3js.org/api\#d3-contour)

Compute contour polygons using marching squares.

- [d3.contours](https://d3js.org/d3-contour/contour#contours) \- create a new contour generator.
- [_contours_](https://d3js.org/d3-contour/contour#_contours) \- compute the contours for a given grid of values.
- [_contours_.contour](https://d3js.org/d3-contour/contour#contours_contour) \- compute a contour for a given value.
- [_contours_.size](https://d3js.org/d3-contour/contour#contours_size) \- set the size of a contour generator.
- [_contours_.smooth](https://d3js.org/d3-contour/contour#contours_smooth) \- set whether or not the generated contours are smoothed.
- [_contours_.thresholds](https://d3js.org/d3-contour/contour#contours_thresholds) \- set the thresholds of a contour generator.
- [d3.contourDensity](https://d3js.org/d3-contour/density#contourDensity) \- create a new density estimator.
- [_density_](https://d3js.org/d3-contour/density#_density) \- estimate the density of a given array of samples.
- [_density_.x](https://d3js.org/d3-contour/density#density_x) \- set the _x_ accessor of the density estimator.
- [_density_.y](https://d3js.org/d3-contour/density#density_y) \- set the _y_ accessor of the density estimator.
- [_density_.weight](https://d3js.org/d3-contour/density#density_weight) \- set the _weight_ accessor of the density estimator.
- [_density_.size](https://d3js.org/d3-contour/density#density_size) \- set the size of the density estimator.
- [_density_.cellSize](https://d3js.org/d3-contour/density#density_cellSize) \- set the cell size of the density estimator.
- [_density_.thresholds](https://d3js.org/d3-contour/density#density_thresholds) \- set the thresholds of the density estimator.
- [_density_.bandwidth](https://d3js.org/d3-contour/density#density_bandwidth) \- set the bandwidth of the density estimator.
- [_density_.contours](https://d3js.org/d3-contour/density#density_contours) \- compute density contours.

## [d3-delaunay](https://d3js.org/d3-delaunay) [​](https://d3js.org/api\#d3-delaunay)

Compute the Voronoi diagram of a set of two-dimensional points.

- [new Delaunay](https://d3js.org/d3-delaunay/delaunay#Delaunay) \- create a delaunay triangulation for an array of point coordinates.
- [Delaunay.from](https://d3js.org/d3-delaunay/delaunay#Delaunay_from) \- create a delaunay triangulation for an iterable of points.
- [_delaunay_.points](https://d3js.org/d3-delaunay/delaunay#delaunay_points) \- the coordinates of the points.
- [_delaunay_.halfedges](https://d3js.org/d3-delaunay/delaunay#delaunay_halfedges) \- the delaunay halfedges.
- [_delaunay_.hull](https://d3js.org/d3-delaunay/delaunay#delaunay_hull) \- the convex hull as point indices.
- [_delaunay_.triangles](https://d3js.org/d3-delaunay/delaunay#delaunay_triangles) \- the delaunay triangles.
- [_delaunay_.inedges](https://d3js.org/d3-delaunay/delaunay#delaunay_inedges) \- the delaunay inedges
- [_delaunay_.find](https://d3js.org/d3-delaunay/delaunay#delaunay_find) \- find the closest point in the delaunay triangulation.
- [_delaunay_.neighbors](https://d3js.org/d3-delaunay/delaunay#delaunay_neighbors) \- the neighbors of a point in the delaunay triangulation.
- [_delaunay_.render](https://d3js.org/d3-delaunay/delaunay#delaunay_render) \- render the edges of the delaunay triangulation.
- [_delaunay_.renderHull](https://d3js.org/d3-delaunay/delaunay#delaunay_renderHull) \- render the convex hull.
- [_delaunay_.renderTriangle](https://d3js.org/d3-delaunay/delaunay#delaunay_renderTriangle) \- render a triangle.
- [_delaunay_.renderPoints](https://d3js.org/d3-delaunay/delaunay#delaunay_renderPoints) \- render the points.
- [_delaunay_.hullPolygon](https://d3js.org/d3-delaunay/delaunay#delaunay_hullPolygon) \- the closed convex hull as point coordinates.
- [_delaunay_.trianglePolygons](https://d3js.org/d3-delaunay/delaunay#delaunay_trianglePolygons) \- iterate over all the triangles as polygons.
- [_delaunay_.trianglePolygon](https://d3js.org/d3-delaunay/delaunay#delaunay_trianglePolygon) \- return a triangle as a polygon.
- [_delaunay_.update](https://d3js.org/d3-delaunay/delaunay#delaunay_update) \- update a delaunay triangulation in place.
- [_delaunay_.voronoi](https://d3js.org/d3-delaunay/voronoi#delaunay_voronoi) \- compute the voronoi diagram associated with a delaunay triangulation.
- [_voronoi_.delaunay](https://d3js.org/d3-delaunay/voronoi#voronoi_delaunay) \- the voronoi diagram’s source delaunay triangulation.
- [_voronoi_.circumcenters](https://d3js.org/d3-delaunay/voronoi#voronoi_circumcenters) \- the triangles’ circumcenters.
- [_voronoi_.vectors](https://d3js.org/d3-delaunay/voronoi#voronoi_vectors) \- directions for the outer (infinite) cells of the voronoi diagram.
- [_voronoi_.xmin](https://d3js.org/d3-delaunay/voronoi#voronoi_bounds) \- set the _xmin_ bound of the extent.
- [_voronoi_.ymin](https://d3js.org/d3-delaunay/voronoi#voronoi_bounds) \- set the _ymin_ bound of the extent.
- [_voronoi_.xmax](https://d3js.org/d3-delaunay/voronoi#voronoi_bounds) \- set the _xmax_ bound of the extent.
- [_voronoi_.ymax](https://d3js.org/d3-delaunay/voronoi#voronoi_bounds) \- set the _ymax_ bound of the extent.
- [_voronoi_.contains](https://d3js.org/d3-delaunay/voronoi#voronoi_contains) \- test whether a point is inside a voronoi cell.
- [_voronoi_.neighbors](https://d3js.org/d3-delaunay/voronoi#voronoi_neighbors) \- the neighbors of a point in the voronoi diagram.
- [_voronoi_.render](https://d3js.org/d3-delaunay/voronoi#voronoi_render) \- render the mesh of voronoi cells.
- [_voronoi_.renderBounds](https://d3js.org/d3-delaunay/voronoi#voronoi_renderBounds) \- render the extent.
- [_voronoi_.renderCell](https://d3js.org/d3-delaunay/voronoi#voronoi_renderCell) \- render a voronoi cell.
- [_voronoi_.cellPolygons](https://d3js.org/d3-delaunay/voronoi#voronoi_cellPolygons) \- iterate over all the cells as polygons.
- [_voronoi_.cellPolygon](https://d3js.org/d3-delaunay/voronoi#voronoi_cellPolygon) \- return a cell as a polygon.
- [_voronoi_.update](https://d3js.org/d3-delaunay/voronoi#voronoi_update) \- update a voronoi diagram in place.

## [d3-dispatch](https://d3js.org/d3-dispatch) [​](https://d3js.org/api\#d3-dispatch)

Separate concerns using named callbacks.

- [d3.dispatch](https://d3js.org/d3-dispatch#dispatch) \- create a custom event dispatcher.
- [_dispatch_.on](https://d3js.org/d3-dispatch#dispatch_on) \- register or unregister an event listener.
- [_dispatch_.copy](https://d3js.org/d3-dispatch#dispatch_copy) \- create a copy of a dispatcher.
- [_dispatch_.call](https://d3js.org/d3-dispatch#dispatch_call) \- dispatch an event to registered listeners.
- [_dispatch_.apply](https://d3js.org/d3-dispatch#dispatch_apply) \- dispatch an event to registered listeners.

## [d3-drag](https://d3js.org/d3-drag) [​](https://d3js.org/api\#d3-drag)

Drag and drop SVG, HTML or Canvas using mouse or touch input.

- [d3.drag](https://d3js.org/d3-drag#drag) \- create a drag behavior.
- [_drag_](https://d3js.org/d3-drag#_drag) \- apply the drag behavior to a selection.
- [_drag_.container](https://d3js.org/d3-drag#drag_container) \- set the coordinate system.
- [_drag_.filter](https://d3js.org/d3-drag#drag_filter) \- ignore some initiating input events.
- [_drag_.touchable](https://d3js.org/d3-drag#drag_touchable) \- set the touch support detector.
- [_drag_.subject](https://d3js.org/d3-drag#drag_subject) \- set the thing being dragged.
- [_drag_.clickDistance](https://d3js.org/d3-drag#drag_clickDistance) \- set the click distance threshold.
- [_drag_.on](https://d3js.org/d3-drag#drag_on) \- listen for drag events.
- [d3.dragDisable](https://d3js.org/d3-drag#dragDisable) \- prevent native drag-and-drop and text selection.
- [d3.dragEnable](https://d3js.org/d3-drag#dragEnable) \- enable native drag-and-drop and text selection.
- [_event_.on](https://d3js.org/d3-drag#event_on) \- listen for drag events on the current gesture.

## [d3-dsv](https://d3js.org/d3-dsv) [​](https://d3js.org/api\#d3-dsv)

Parse and format delimiter-separated values, most commonly CSV and TSV.

- [d3.csvParse](https://d3js.org/d3-dsv#csvParse) \- parse the given CSV string, returning an array of objects.
- [d3.csvParseRows](https://d3js.org/d3-dsv#csvParseRows) \- parse the given CSV string, returning an array of rows.
- [d3.csvFormat](https://d3js.org/d3-dsv#csvFormat) \- format the given array of objects as CSV.
- [d3.csvFormatBody](https://d3js.org/d3-dsv#csvFormatBody) \- format the given array of objects as CSV.
- [d3.csvFormatRows](https://d3js.org/d3-dsv#csvFormatRows) \- format the given array of rows as CSV.
- [d3.csvFormatRow](https://d3js.org/d3-dsv#csvFormatRow) \- format the given row as CSV.
- [d3.csvFormatValue](https://d3js.org/d3-dsv#csvFormatValue) \- format the given value as CSV.
- [d3.tsvParse](https://d3js.org/d3-dsv#tsvParse) \- parse the given TSV string, returning an array of objects.
- [d3.tsvParseRows](https://d3js.org/d3-dsv#tsvParseRows) \- parse the given TSV string, returning an array of rows.
- [d3.tsvFormat](https://d3js.org/d3-dsv#tsvFormat) \- format the given array of objects as TSV.
- [d3.tsvFormatBody](https://d3js.org/d3-dsv#tsvFormatBody) \- format the given array of objects as TSV.
- [d3.tsvFormatRows](https://d3js.org/d3-dsv#tsvFormatRows) \- format the given array of rows as TSV.
- [d3.tsvFormatRow](https://d3js.org/d3-dsv#tsvFormatRow) \- format the given row as TSV.
- [d3.tsvFormatValue](https://d3js.org/d3-dsv#tsvFormatValue) \- format the given value as TSV.
- [d3.dsvFormat](https://d3js.org/d3-dsv#dsvFormat) \- create a new parser and formatter for the given delimiter.
- [_dsv_.parse](https://d3js.org/d3-dsv#dsv_parse) \- parse the given string, returning an array of objects.
- [_dsv_.parseRows](https://d3js.org/d3-dsv#dsv_parseRows) \- parse the given string, returning an array of rows.
- [_dsv_.format](https://d3js.org/d3-dsv#dsv_format) \- format the given array of objects.
- [_dsv_.formatBody](https://d3js.org/d3-dsv#dsv_formatBody) \- format the given array of objects.
- [_dsv_.formatRows](https://d3js.org/d3-dsv#dsv_formatRows) \- format the given array of rows.
- [_dsv_.formatRow](https://d3js.org/d3-dsv#dsv_formatRow) \- format the given row.
- [_dsv_.formatValue](https://d3js.org/d3-dsv#dsv_formatValue) \- format the given value.
- [d3.autoType](https://d3js.org/d3-dsv#autoType) \- automatically infer value types for the given object.

## [d3-ease](https://d3js.org/d3-ease) [​](https://d3js.org/api\#d3-ease)

Easing functions for smooth animation.

- [_ease_](https://d3js.org/d3-ease#_ease) \- ease the given normalized time.
- [d3.easeLinear](https://d3js.org/d3-ease#easeLinear) \- linear easing; the identity function.
- [d3.easePolyIn](https://d3js.org/d3-ease#easePolyIn) \- polynomial easing; raises time to the given power.
- [d3.easePolyOut](https://d3js.org/d3-ease#easePolyOut) \- reverse polynomial easing.
- [d3.easePoly](https://d3js.org/d3-ease#easePoly) \- an alias for easePolyInOut.
- [d3.easePolyInOut](https://d3js.org/d3-ease#easePolyInOut) \- symmetric polynomial easing.
- [_poly_.exponent](https://d3js.org/d3-ease#easePoly_exponent) \- specify the polynomial exponent.
- [d3.easeQuadIn](https://d3js.org/d3-ease#easeQuadIn) \- quadratic easing; squares time.
- [d3.easeQuadOut](https://d3js.org/d3-ease#easeQuadOut) \- reverse quadratic easing.
- [d3.easeQuad](https://d3js.org/d3-ease#easeQuad) \- an alias for easeQuadInOut.
- [d3.easeQuadInOut](https://d3js.org/d3-ease#easeQuadInOut) \- symmetric quadratic easing.
- [d3.easeCubicIn](https://d3js.org/d3-ease#easeCubicIn) \- cubic easing; cubes time.
- [d3.easeCubicOut](https://d3js.org/d3-ease#easeCubicOut) \- reverse cubic easing.
- [d3.easeCubic](https://d3js.org/d3-ease#easeCubic) \- an alias for easeCubicInOut.
- [d3.easeCubicInOut](https://d3js.org/d3-ease#easeCubicInOut) \- symmetric cubic easing.
- [d3.easeSinIn](https://d3js.org/d3-ease#easeSinIn) \- sinusoidal easing.
- [d3.easeSinOut](https://d3js.org/d3-ease#easeSinOut) \- reverse sinusoidal easing.
- [d3.easeSin](https://d3js.org/d3-ease#easeSin) \- an alias for easeSinInOut.
- [d3.easeSinInOut](https://d3js.org/d3-ease#easeSinInOut) \- symmetric sinusoidal easing.
- [d3.easeExpIn](https://d3js.org/d3-ease#easeExpIn) \- exponential easing.
- [d3.easeExpOut](https://d3js.org/d3-ease#easeExpOut) \- reverse exponential easing.
- [d3.easeExp](https://d3js.org/d3-ease#easeExp) \- an alias for easeExpInOut.
- [d3.easeExpInOut](https://d3js.org/d3-ease#easeExpInOut) \- symmetric exponential easing.
- [d3.easeCircleIn](https://d3js.org/d3-ease#easeCircleIn) \- circular easing.
- [d3.easeCircleOut](https://d3js.org/d3-ease#easeCircleOut) \- reverse circular easing.
- [d3.easeCircle](https://d3js.org/d3-ease#easeCircle) \- an alias for easeCircleInOut.
- [d3.easeCircleInOut](https://d3js.org/d3-ease#easeCircleInOut) \- symmetric circular easing.
- [d3.easeElasticIn](https://d3js.org/d3-ease#easeElasticIn) \- elastic easing, like a rubber band.
- [d3.easeElastic](https://d3js.org/d3-ease#easeElastic) \- an alias for easeElasticOut.
- [d3.easeElasticOut](https://d3js.org/d3-ease#easeElasticOut) \- reverse elastic easing.
- [d3.easeElasticInOut](https://d3js.org/d3-ease#easeElasticInOut) \- symmetric elastic easing.
- [_elastic_.amplitude](https://d3js.org/d3-ease#easeElastic_amplitude) \- specify the elastic amplitude.
- [_elastic_.period](https://d3js.org/d3-ease#easeElastic_period) \- specify the elastic period.
- [d3.easeBackIn](https://d3js.org/d3-ease#easeBackIn) \- anticipatory easing, like a dancer bending his knees before jumping.
- [d3.easeBackOut](https://d3js.org/d3-ease#easeBackOut) \- reverse anticipatory easing.
- [d3.easeBack](https://d3js.org/d3-ease#easeBack) \- an alias for easeBackInOut.
- [d3.easeBackInOut](https://d3js.org/d3-ease#easeBackInOut) \- symmetric anticipatory easing.
- [_back_.overshoot](https://d3js.org/d3-ease#easeBack_overshoot) \- specify the amount of overshoot.
- [d3.easeBounceIn](https://d3js.org/d3-ease#easeBounceIn) \- bounce easing, like a rubber ball.
- [d3.easeBounce](https://d3js.org/d3-ease#easeBounce) \- an alias for easeBounceOut.
- [d3.easeBounceOut](https://d3js.org/d3-ease#easeBounceOut) \- reverse bounce easing.
- [d3.easeBounceInOut](https://d3js.org/d3-ease#easeBounceInOut) \- symmetric bounce easing.

## [d3-fetch](https://d3js.org/d3-fetch) [​](https://d3js.org/api\#d3-fetch)

Convenience methods on top of the Fetch API.

- [d3.blob](https://d3js.org/d3-fetch#blob) \- get a file as a blob.
- [d3.buffer](https://d3js.org/d3-fetch#buffer) \- get a file as an array buffer.
- [d3.csv](https://d3js.org/d3-fetch#csv) \- get a comma-separated values (CSV) file.
- [d3.dsv](https://d3js.org/d3-fetch#dsv) \- get a delimiter-separated values (CSV) file.
- [d3.html](https://d3js.org/d3-fetch#html) \- get an HTML file.
- [d3.image](https://d3js.org/d3-fetch#image) \- get an image.
- [d3.json](https://d3js.org/d3-fetch#json) \- get a JSON file.
- [d3.svg](https://d3js.org/d3-fetch#svg) \- get an SVG file.
- [d3.text](https://d3js.org/d3-fetch#text) \- get a plain text file.
- [d3.tsv](https://d3js.org/d3-fetch#tsv) \- get a tab-separated values (TSV) file.
- [d3.xml](https://d3js.org/d3-fetch#xml) \- get an XML file.

## [d3-force](https://d3js.org/d3-force) [​](https://d3js.org/api\#d3-force)

Force-directed graph layout using velocity Verlet integration.

- [d3.forceSimulation](https://d3js.org/d3-force/simulation#forceSimulation) \- create a new force simulation.
- [_simulation_.restart](https://d3js.org/d3-force/simulation#simulation_restart) \- reheat and restart the simulation’s timer.
- [_simulation_.stop](https://d3js.org/d3-force/simulation#simulation_stop) \- stop the simulation’s timer.
- [_simulation_.tick](https://d3js.org/d3-force/simulation#simulation_tick) \- advance the simulation one step.
- [_simulation_.nodes](https://d3js.org/d3-force/simulation#simulation_nodes) \- set the simulation’s nodes.
- [_simulation_.alpha](https://d3js.org/d3-force/simulation#simulation_alpha) \- set the current alpha.
- [_simulation_.alphaMin](https://d3js.org/d3-force/simulation#simulation_alphaMin) \- set the minimum alpha threshold.
- [_simulation_.alphaDecay](https://d3js.org/d3-force/simulation#simulation_alphaDecay) \- set the alpha exponential decay rate.
- [_simulation_.alphaTarget](https://d3js.org/d3-force/simulation#simulation_alphaTarget) \- set the target alpha.
- [_simulation_.velocityDecay](https://d3js.org/d3-force/simulation#simulation_velocityDecay) \- set the velocity decay rate.
- [_simulation_.force](https://d3js.org/d3-force/simulation#simulation_force) \- add or remove a force.
- [_simulation_.find](https://d3js.org/d3-force/simulation#simulation_find) \- find the closest node to the given position.
- [_simulation_.randomSource](https://d3js.org/d3-force/simulation#simulation_randomSource) \- set the simulation’s random source.
- [_simulation_.on](https://d3js.org/d3-force/simulation#simulation_on) \- add or remove an event listener.
- [_force_](https://d3js.org/d3-force/simulation#_force) \- apply the force.
- [_force_.initialize](https://d3js.org/d3-force/simulation#force_initialize) \- initialize the force with the given nodes.
- [d3.forceCenter](https://d3js.org/d3-force/center#forceCenter) \- create a centering force.
- [_center_.x](https://d3js.org/d3-force/center#center_x) \- set the center _x_-coordinate.
- [_center_.y](https://d3js.org/d3-force/center#center_y) \- set the center y coordinate.
- [_center_.strength](https://d3js.org/d3-force/center#center_strength) \- set the strength of the centering force.
- [d3.forceCollide](https://d3js.org/d3-force/collide#forceCollide) \- create a circle collision force.
- [_collide_.radius](https://d3js.org/d3-force/collide#collide_radius) \- set the circle radius.
- [_collide_.strength](https://d3js.org/d3-force/collide#collide_strength) \- set the collision resolution strength.
- [_collide_.iterations](https://d3js.org/d3-force/collide#collide_iterations) \- set the number of iterations.
- [d3.forceLink](https://d3js.org/d3-force/link#forceLink) \- create a link force.
- [_link_.links](https://d3js.org/d3-force/link#link_links) \- set the array of links.
- [_link_.id](https://d3js.org/d3-force/link#link_id) \- link nodes by numeric index or string identifier.
- [_link_.distance](https://d3js.org/d3-force/link#link_distance) \- set the link distance.
- [_link_.strength](https://d3js.org/d3-force/link#link_strength) \- set the link strength.
- [_link_.iterations](https://d3js.org/d3-force/link#link_iterations) \- set the number of iterations.
- [d3.forceManyBody](https://d3js.org/d3-force/many-body#forceManyBody) \- create a many-body force.
- [_manyBody_.strength](https://d3js.org/d3-force/many-body#manyBody_strength) \- set the force strength.
- [_manyBody_.theta](https://d3js.org/d3-force/many-body#manyBody_theta) \- set the Barnes–Hut approximation accuracy.
- [_manyBody_.distanceMin](https://d3js.org/d3-force/many-body#manyBody_distanceMin) \- limit the force when nodes are close.
- [_manyBody_.distanceMax](https://d3js.org/d3-force/many-body#manyBody_distanceMax) \- limit the force when nodes are far.
- [d3.forceX](https://d3js.org/d3-force/position#forceX) \- create an _x_-positioning force.
- [_x_.strength](https://d3js.org/d3-force/position#x_strength) \- set the force strength.
- [_x_.x](https://d3js.org/d3-force/position#x_x) \- set the target _x_-coordinate.
- [d3.forceY](https://d3js.org/d3-force/position#forceY) \- create an _y_-positioning force.
- [_y_.strength](https://d3js.org/d3-force/position#y_strength) \- set the force strength.
- [_y_.y](https://d3js.org/d3-force/position#y_y) \- set the target y coordinate.
- [d3.forceRadial](https://d3js.org/d3-force/position#forceRadial) \- create a radial positioning force.
- [_radial_.strength](https://d3js.org/d3-force/position#radial_strength) \- set the force strength.
- [_radial_.radius](https://d3js.org/d3-force/position#radial_radius) \- set the target radius.
- [_radial_.x](https://d3js.org/d3-force/position#radial_x) \- set the target center _x_-coordinate.
- [_radial_.y](https://d3js.org/d3-force/position#radial_y) \- set the target center y coordinate.

## [d3-format](https://d3js.org/d3-format) [​](https://d3js.org/api\#d3-format)

Format numbers for human consumption.

- [d3.format](https://d3js.org/d3-format#format) \- alias for _locale_.format on the default locale.
- [d3.formatPrefix](https://d3js.org/d3-format#formatPrefix) \- alias for _locale_.formatPrefix on the default locale.
- [_locale_.format](https://d3js.org/d3-format#locale_format) \- create a number format.
- [_locale_.formatPrefix](https://d3js.org/d3-format#locale_formatPrefix) \- create a SI-prefix number format.
- [d3.formatSpecifier](https://d3js.org/d3-format#formatSpecifier) \- parse a number format specifier.
- [new d3.FormatSpecifier](https://d3js.org/d3-format#FormatSpecifier) \- augments a number format specifier object.
- [d3.precisionFixed](https://d3js.org/d3-format#precisionFixed) \- compute decimal precision for fixed-point notation.
- [d3.precisionPrefix](https://d3js.org/d3-format#precisionPrefix) \- compute decimal precision for SI-prefix notation.
- [d3.precisionRound](https://d3js.org/d3-format#precisionRound) \- compute significant digits for rounded notation.
- [d3.formatLocale](https://d3js.org/d3-format#formatLocale) \- define a custom locale.
- [d3.formatDefaultLocale](https://d3js.org/d3-format#formatDefaultLocale) \- define the default locale.

## [d3-geo](https://d3js.org/d3-geo) [​](https://d3js.org/api\#d3-geo)

Geographic projections, shapes and math.

### [Paths](https://d3js.org/d3-geo/path) [​](https://d3js.org/api\#paths)

- [d3.geoPath](https://d3js.org/d3-geo/path#geoPath) \- create a new geographic path generator.
- [_path_](https://d3js.org/d3-geo/path#_path) \- project and render the specified feature.
- [_path_.area](https://d3js.org/d3-geo/path#path_area) \- compute the projected planar area of a given feature.
- [_path_.bounds](https://d3js.org/d3-geo/path#path_bounds) \- compute the projected planar bounding box of a given feature.
- [_path_.centroid](https://d3js.org/d3-geo/path#path_centroid) \- compute the projected planar centroid of a given feature.
- [_path_.digits](https://d3js.org/d3-geo/path#path_digits) \- set the output precision.
- [_path_.measure](https://d3js.org/d3-geo/path#path_measure) \- compute the projected planar length of a given feature.
- [_path_.projection](https://d3js.org/d3-geo/path#path_projection) \- set the geographic projection.
- [_path_.context](https://d3js.org/d3-geo/path#path_context) \- set the render context.
- [_path_.pointRadius](https://d3js.org/d3-geo/path#path_pointRadius) \- set the radius to display point features.

### [Projections](https://d3js.org/d3-geo/projection) [​](https://d3js.org/api\#projections)

- [_projection_](https://d3js.org/d3-geo/projection#_projection) \- project the specified point from the sphere to the plane.
- [_projection_.invert](https://d3js.org/d3-geo/projection#projection_invert) \- unproject the specified point from the plane to the sphere.
- [_projection_.stream](https://d3js.org/d3-geo/projection#projection_stream) \- wrap the specified stream to project geometry.
- [_projection_.preclip](https://d3js.org/d3-geo/projection#projection_preclip) \- set the projection’s spherical clipping function.
- [_projection_.postclip](https://d3js.org/d3-geo/projection#projection_postclip) \- set the projection’s cartesian clipping function.
- [_projection_.clipAngle](https://d3js.org/d3-geo/projection#projection_clipAngle) \- set the radius of the clip circle.
- [_projection_.clipExtent](https://d3js.org/d3-geo/projection#projection_clipExtent) \- set the viewport clip extent, in pixels.
- [_projection_.scale](https://d3js.org/d3-geo/projection#projection_scale) \- set the scale factor.
- [_projection_.translate](https://d3js.org/d3-geo/projection#projection_translate) \- set the translation offset.
- [_projection_.center](https://d3js.org/d3-geo/projection#projection_center) \- set the center point.
- [_projection_.angle](https://d3js.org/d3-geo/projection#projection_angle) \- set the post-projection rotation.
- [_projection_.reflectX](https://d3js.org/d3-geo/projection#projection_reflectX) \- reflect the _x_-dimension.
- [_projection_.reflectY](https://d3js.org/d3-geo/projection#projection_reflectY) \- reflect the _y_-dimension.
- [_projection_.rotate](https://d3js.org/d3-geo/projection#projection_rotate) \- set the three-axis spherical rotation angles.
- [_projection_.precision](https://d3js.org/d3-geo/projection#projection_precision) \- set the precision threshold for adaptive sampling.
- [_projection_.fitExtent](https://d3js.org/d3-geo/projection#projection_fitExtent) \- set the scale and translate to fit a GeoJSON object.
- [_projection_.fitSize](https://d3js.org/d3-geo/projection#projection_fitSize) \- set the scale and translate to fit a GeoJSON object.
- [_projection_.fitWidth](https://d3js.org/d3-geo/projection#projection_fitWidth) \- set the scale and translate to fit a GeoJSON object.
- [_projection_.fitHeight](https://d3js.org/d3-geo/projection#projection_fitHeight) \- set the scale and translate to fit a GeoJSON object.

#### [Raw projections](https://d3js.org/d3-geo/projection\#raw-projections) [​](https://d3js.org/api\#raw-projections)

- [_project_](https://d3js.org/d3-geo/projection#_project) \- project the specified point from the sphere to the plane.
- [_project_.invert](https://d3js.org/d3-geo/projection#project_invert) \- unproject the specified point from the plane to the sphere.
- [d3.geoProjection](https://d3js.org/d3-geo/projection#geoProjection) \- create a custom projection.
- [d3.geoProjectionMutator](https://d3js.org/d3-geo/projection#geoProjectionMutator) \- create a custom configurable projection.
- [d3.geoTransform](https://d3js.org/d3-geo/projection#geoTransform) \- define a custom geometry transform.
- [d3.geoIdentity](https://d3js.org/d3-geo/projection#geoIdentity) \- scale, translate or clip planar geometry.
- [d3.geoClipAntimeridian](https://d3js.org/d3-geo/projection#geoClipAntimeridian) \- cuts spherical geometries that cross the antimeridian.
- [d3.geoClipCircle](https://d3js.org/d3-geo/projection#geoClipCircle) \- clips spherical geometries to a small circle.
- [d3.geoClipRectangle](https://d3js.org/d3-geo/projection#geoClipRectangle) \- clips planar geometries to a rectangular viewport.

#### [Azimuthal projections](https://d3js.org/d3-geo/azimuthal) [​](https://d3js.org/api\#azimuthal-projections)

- [d3.geoAzimuthalEqualArea](https://d3js.org/d3-geo/azimuthal#geoAzimuthalEqualArea) \- the azimuthal equal-area projection.
- [d3.geoAzimuthalEquidistant](https://d3js.org/d3-geo/azimuthal#geoAzimuthalEquidistant) \- the azimuthal equidistant projection.
- [d3.geoGnomonic](https://d3js.org/d3-geo/azimuthal#geoGnomonic) \- the gnomonic projection.
- [d3.geoOrthographic](https://d3js.org/d3-geo/azimuthal#geoOrthographic) \- the azimuthal orthographic projection.
- [d3.geoStereographic](https://d3js.org/d3-geo/azimuthal#geoStereographic) \- the azimuthal stereographic projection.

#### [Conic projections](https://d3js.org/d3-geo/conic) [​](https://d3js.org/api\#conic-projections)

- [_conic_.parallels](https://d3js.org/d3-geo/conic#conic_parallels) \- set the two standard parallels.
- [d3.geoConicConformal](https://d3js.org/d3-geo/conic#geoConicConformal) \- the conic conformal projection.
- [d3.geoConicEqualArea](https://d3js.org/d3-geo/conic#geoConicEqualArea) \- the conic equal-area (Albers) projection.
- [d3.geoConicEquidistant](https://d3js.org/d3-geo/conic#geoConicEquidistant) \- the conic equidistant projection.
- [d3.geoAlbers](https://d3js.org/d3-geo/conic#geoAlbers) \- the Albers equal-area conic projection.
- [d3.geoAlbersUsa](https://d3js.org/d3-geo/conic#geoAlbersUsa) \- a composite Albers projection for the United States.

#### [Cylindrical projections](https://d3js.org/d3-geo/cylindrical) [​](https://d3js.org/api\#cylindrical-projections)

- [d3.geoEquirectangular](https://d3js.org/d3-geo/cylindrical#geoEquirectangular) \- the equirectangular (plate carreé) projection.
- [d3.geoMercator](https://d3js.org/d3-geo/cylindrical#geoMercator) \- the spherical Mercator projection.
- [d3.geoTransverseMercator](https://d3js.org/d3-geo/cylindrical#geoTransverseMercator) \- the transverse spherical Mercator projection.
- [d3.geoEqualEarth](https://d3js.org/d3-geo/cylindrical#geoEqualEarth) \- the Equal Earth projection.
- [d3.geoNaturalEarth1](https://d3js.org/d3-geo/cylindrical#geoNaturalEarth1) \- the Equal Earth projection, version 1.

### [Streams](https://d3js.org/d3-geo/stream) [​](https://d3js.org/api\#streams)

- [d3.geoStream](https://d3js.org/d3-geo/stream#geoStream) \- convert a GeoJSON object to a geometry stream.
- [_stream_.point](https://d3js.org/d3-geo/stream#stream_point) \- indicates a point with the specified coordinates.
- [_stream_.lineStart](https://d3js.org/d3-geo/stream#stream_lineStart) \- indicates the start of a line or ring.
- [_stream_.lineEnd](https://d3js.org/d3-geo/stream#stream_lineEnd) \- indicates the end of a line or ring.
- [_stream_.polygonStart](https://d3js.org/d3-geo/stream#stream_polygonStart) \- indicates the start of a polygon.
- [_stream_.polygonEnd](https://d3js.org/d3-geo/stream#stream_polygonEnd) \- indicates the end of a polygon.
- [_stream_.sphere](https://d3js.org/d3-geo/stream#stream_sphere) \- indicates the sphere.

### [Spherical shapes](https://d3js.org/d3-geo/shape) [​](https://d3js.org/api\#spherical-shapes)

- [d3.geoGraticule](https://d3js.org/d3-geo/shape#geoGraticule) \- create a graticule generator.
- [_graticule_](https://d3js.org/d3-geo/shape#_graticule) \- generate a MultiLineString of meridians and parallels.
- [_graticule_.lines](https://d3js.org/d3-geo/shape#graticule_lines) \- generate an array of LineStrings of meridians and parallels.
- [_graticule_.outline](https://d3js.org/d3-geo/shape#graticule_outline) \- generate a Polygon of the graticule’s extent.
- [_graticule_.extent](https://d3js.org/d3-geo/shape#graticule_extent) \- get or set the major & minor extents.
- [_graticule_.extentMajor](https://d3js.org/d3-geo/shape#graticule_extentMajor) \- get or set the major extent.
- [_graticule_.extentMinor](https://d3js.org/d3-geo/shape#graticule_extentMinor) \- get or set the minor extent.
- [_graticule_.step](https://d3js.org/d3-geo/shape#graticule_step) \- get or set the major & minor step intervals.
- [_graticule_.stepMajor](https://d3js.org/d3-geo/shape#graticule_stepMajor) \- get or set the major step intervals.
- [_graticule_.stepMinor](https://d3js.org/d3-geo/shape#graticule_stepMinor) \- get or set the minor step intervals.
- [_graticule_.precision](https://d3js.org/d3-geo/shape#graticule_precision) \- get or set the latitudinal precision.
- [d3.geoGraticule10](https://d3js.org/d3-geo/shape#geoGraticule10) \- generate the default 10° global graticule.
- [d3.geoCircle](https://d3js.org/d3-geo/shape#geoCircle) \- create a circle generator.
- [_circle_](https://d3js.org/d3-geo/shape#_circle) \- generate a piecewise circle as a Polygon.
- [_circle_.center](https://d3js.org/d3-geo/shape#circle_center) \- specify the circle center in latitude and longitude.
- [_circle_.radius](https://d3js.org/d3-geo/shape#circle_radius) \- specify the angular radius in degrees.
- [_circle_.precision](https://d3js.org/d3-geo/shape#circle_precision) \- specify the precision of the piecewise circle.

### [Spherical math](https://d3js.org/d3-geo/math) [​](https://d3js.org/api\#spherical-math)

- [d3.geoArea](https://d3js.org/d3-geo/math#geoArea) \- compute the spherical area of a given feature.
- [d3.geoBounds](https://d3js.org/d3-geo/math#geoBounds) \- compute the latitude-longitude bounding box for a given feature.
- [d3.geoCentroid](https://d3js.org/d3-geo/math#geoCentroid) \- compute the spherical centroid of a given feature.
- [d3.geoDistance](https://d3js.org/d3-geo/math#geoDistance) \- compute the great-arc distance between two points.
- [d3.geoLength](https://d3js.org/d3-geo/math#geoLength) \- compute the length of a line string or the perimeter of a polygon.
- [d3.geoInterpolate](https://d3js.org/d3-geo/math#geoInterpolate) \- interpolate between two points along a great arc.
- [d3.geoContains](https://d3js.org/d3-geo/math#geoContains) \- test whether a point is inside a given feature.
- [d3.geoRotation](https://d3js.org/d3-geo/math#geoRotation) \- create a rotation function for the specified angles.

## [d3-hierarchy](https://d3js.org/d3-hierarchy) [​](https://d3js.org/api\#d3-hierarchy)

Layout algorithms for visualizing hierarchical data.

- [d3.hierarchy](https://d3js.org/d3-hierarchy/hierarchy#hierarchy) \- constructs a root node from hierarchical data.
- [_node_.ancestors](https://d3js.org/d3-hierarchy/hierarchy#node_ancestors) \- generate an array of ancestors.
- [_node_.descendants](https://d3js.org/d3-hierarchy/hierarchy#node_descendants) \- generate an array of descendants.
- [_node_.leaves](https://d3js.org/d3-hierarchy/hierarchy#node_leaves) \- generate an array of leaves.
- [_node_.find](https://d3js.org/d3-hierarchy/hierarchy#node_find) \- find a node in the hierarchy.
- [_node_.path](https://d3js.org/d3-hierarchy/hierarchy#node_path) \- generate the shortest path to another node.
- [_node_.links](https://d3js.org/d3-hierarchy/hierarchy#node_links) \- generate an array of links.
- [_node_.sum](https://d3js.org/d3-hierarchy/hierarchy#node_sum) \- evaluate and aggregate quantitative values.
- [_node_.count](https://d3js.org/d3-hierarchy/hierarchy#node_count) \- count the number of leaves.
- [_node_.sort](https://d3js.org/d3-hierarchy/hierarchy#node_sort) \- sort all descendant siblings.
- [_node_\[Symbol.iterator\]](https://d3js.org/d3-hierarchy/hierarchy#node_iterator) \- iterate on a hierarchy.
- [_node_.each](https://d3js.org/d3-hierarchy/hierarchy#node_each) \- breadth-first traversal.
- [_node_.eachAfter](https://d3js.org/d3-hierarchy/hierarchy#node_eachAfter) \- post-order traversal.
- [_node_.eachBefore](https://d3js.org/d3-hierarchy/hierarchy#node_eachBefore) \- pre-order traversal.
- [_node_.copy](https://d3js.org/d3-hierarchy/hierarchy#node_copy) \- copy a hierarchy.
- [d3.stratify](https://d3js.org/d3-hierarchy/stratify#stratify) \- create a new stratify operator.
- [_stratify_](https://d3js.org/d3-hierarchy/stratify#_stratify) \- construct a root node from tabular data.
- [_stratify_.id](https://d3js.org/d3-hierarchy/stratify#stratify_id) \- set the node id accessor.
- [_stratify_.parentId](https://d3js.org/d3-hierarchy/stratify#stratify_parentId) \- set the parent node id accessor.
- [_stratify_.path](https://d3js.org/d3-hierarchy/stratify#stratify_path) \- set the path accessor.
- [d3.cluster](https://d3js.org/d3-hierarchy/cluster#cluster) \- create a new cluster (dendrogram) layout.
- [_cluster_](https://d3js.org/d3-hierarchy/cluster#_cluster) \- layout the specified hierarchy in a dendrogram.
- [_cluster_.size](https://d3js.org/d3-hierarchy/cluster#cluster_size) \- set the layout size.
- [_cluster_.nodeSize](https://d3js.org/d3-hierarchy/cluster#cluster_nodeSize) \- set the node size.
- [_cluster_.separation](https://d3js.org/d3-hierarchy/cluster#cluster_separation) \- set the separation between leaves.
- [d3.tree](https://d3js.org/d3-hierarchy/tree#tree) \- create a new tidy tree layout.
- [_tree_](https://d3js.org/d3-hierarchy/tree#_tree) \- layout the specified hierarchy in a tidy tree.
- [_tree_.size](https://d3js.org/d3-hierarchy/tree#tree_size) \- set the layout size.
- [_tree_.nodeSize](https://d3js.org/d3-hierarchy/tree#tree_nodeSize) \- set the node size.
- [_tree_.separation](https://d3js.org/d3-hierarchy/tree#tree_separation) \- set the separation between nodes.
- [d3.treemap](https://d3js.org/d3-hierarchy/treemap#treemap) \- create a new treemap layout.
- [_treemap_](https://d3js.org/d3-hierarchy/treemap#_treemap) \- layout the specified hierarchy as a treemap.
- [_treemap_.tile](https://d3js.org/d3-hierarchy/treemap#treemap_tile) \- set the tiling method.
- [_treemap_.size](https://d3js.org/d3-hierarchy/treemap#treemap_size) \- set the layout size.
- [_treemap_.round](https://d3js.org/d3-hierarchy/treemap#treemap_round) \- set whether the output coordinates are rounded.
- [_treemap_.padding](https://d3js.org/d3-hierarchy/treemap#treemap_padding) \- set the padding.
- [_treemap_.paddingInner](https://d3js.org/d3-hierarchy/treemap#treemap_paddingInner) \- set the padding between siblings.
- [_treemap_.paddingOuter](https://d3js.org/d3-hierarchy/treemap#treemap_paddingOuter) \- set the padding between parent and children.
- [_treemap_.paddingTop](https://d3js.org/d3-hierarchy/treemap#treemap_paddingTop) \- set the padding between the parent’s top edge and children.
- [_treemap_.paddingRight](https://d3js.org/d3-hierarchy/treemap#treemap_paddingRight) \- set the padding between the parent’s right edge and children.
- [_treemap_.paddingBottom](https://d3js.org/d3-hierarchy/treemap#treemap_paddingBottom) \- set the padding between the parent’s bottom edge and children.
- [_treemap_.paddingLeft](https://d3js.org/d3-hierarchy/treemap#treemap_paddingLeft) \- set the padding between the parent’s left edge and children.
- [d3.treemapBinary](https://d3js.org/d3-hierarchy/treemap#treemapBinary) \- tile using a balanced binary tree.
- [d3.treemapDice](https://d3js.org/d3-hierarchy/treemap#treemapDice) \- tile into a horizontal row.
- [d3.treemapSlice](https://d3js.org/d3-hierarchy/treemap#treemapSlice) \- tile into a vertical column.
- [d3.treemapSliceDice](https://d3js.org/d3-hierarchy/treemap#treemapSliceDice) \- alternate between slicing and dicing.
- [d3.treemapSquarify](https://d3js.org/d3-hierarchy/treemap#treemapSquarify) \- tile using squarified rows per Bruls _et. al._
- [d3.treemapResquarify](https://d3js.org/d3-hierarchy/treemap#treemapResquarify) \- like d3.treemapSquarify, but performs stable updates.
- [_squarify_.ratio](https://d3js.org/d3-hierarchy/treemap#squarify_ratio) \- set the desired rectangle aspect ratio.
- [d3.partition](https://d3js.org/d3-hierarchy/partition#partition) \- create a new partition (icicle or sunburst) layout.
- [_partition_](https://d3js.org/d3-hierarchy/partition#_partition) \- layout the specified hierarchy as a partition diagram.
- [_partition_.size](https://d3js.org/d3-hierarchy/partition#partition_size) \- set the layout size.
- [_partition_.round](https://d3js.org/d3-hierarchy/partition#partition_round) \- set whether the output coordinates are rounded.
- [_partition_.padding](https://d3js.org/d3-hierarchy/partition#partition_padding) \- set the padding.
- [d3.pack](https://d3js.org/d3-hierarchy/pack#pack) \- create a new circle-packing layout.
- [_pack_](https://d3js.org/d3-hierarchy/pack#_pack) \- layout the specified hierarchy using circle-packing.
- [_pack_.radius](https://d3js.org/d3-hierarchy/pack#pack_radius) \- set the radius accessor.
- [_pack_.size](https://d3js.org/d3-hierarchy/pack#pack_size) \- set the layout size.
- [_pack_.padding](https://d3js.org/d3-hierarchy/pack#pack_padding) \- set the padding.
- [d3.packSiblings](https://d3js.org/d3-hierarchy/pack#packSiblings) \- pack the specified array of circles.
- [d3.packEnclose](https://d3js.org/d3-hierarchy/pack#packEnclose) \- enclose the specified array of circles.

## [d3-interpolate](https://d3js.org/d3-interpolate) [​](https://d3js.org/api\#d3-interpolate)

Interpolate numbers, colors, strings, arrays, objects, whatever!

### [Value interpolation](https://d3js.org/d3-interpolate/value) [​](https://d3js.org/api\#value-interpolation)

- [d3.interpolate](https://d3js.org/d3-interpolate/value#interpolate) \- interpolate arbitrary values.
- [d3.interpolateNumber](https://d3js.org/d3-interpolate/value#interpolateNumber) \- interpolate numbers.
- [d3.interpolateRound](https://d3js.org/d3-interpolate/value#interpolateRound) \- interpolate integers.
- [d3.interpolateString](https://d3js.org/d3-interpolate/value#interpolateString) \- interpolate strings with embedded numbers.
- [d3.interpolateDate](https://d3js.org/d3-interpolate/value#interpolateDate) \- interpolate dates.
- [d3.interpolateArray](https://d3js.org/d3-interpolate/value#interpolateArray) \- interpolate arrays of arbitrary values.
- [d3.interpolateNumberArray](https://d3js.org/d3-interpolate/value#interpolateNumberArray) \- interpolate arrays of numbers.
- [d3.interpolateObject](https://d3js.org/d3-interpolate/value#interpolateObject) \- interpolate arbitrary objects.
- [d3.interpolateBasis](https://d3js.org/d3-interpolate/value#interpolateBasis) \- generate a B-spline through a set of values.
- [d3.interpolateBasisClosed](https://d3js.org/d3-interpolate/value#interpolateBasisClosed) \- generate a closed B-spline through a set of values.
- [d3.interpolateDiscrete](https://d3js.org/d3-interpolate/value#interpolateDiscrete) \- generate a discrete interpolator from a set of values.
- [d3.quantize](https://d3js.org/d3-interpolate/value#quantize) \- generate uniformly-spaced samples from an interpolator.
- [d3.piecewise](https://d3js.org/d3-interpolate/value#piecewise) \- generate a piecewise linear interpolator from a set of values.

### [Color interpolation](https://d3js.org/d3-interpolate/color) [​](https://d3js.org/api\#color-interpolation)

- [d3.interpolateRgb](https://d3js.org/d3-interpolate/color#interpolateRgb) \- interpolate RGB colors.
- [d3.interpolateRgbBasis](https://d3js.org/d3-interpolate/color#interpolateRgbBasis) \- generate a B-spline through a set of colors.
- [d3.interpolateRgbBasisClosed](https://d3js.org/d3-interpolate/color#interpolateRgbBasisClosed) \- generate a closed B-spline through a set of colors.
- [d3.interpolateHsl](https://d3js.org/d3-interpolate/color#interpolateHsl) \- interpolate HSL colors.
- [d3.interpolateHslLong](https://d3js.org/d3-interpolate/color#interpolateHslLong) \- interpolate HSL colors, the long way.
- [d3.interpolateLab](https://d3js.org/d3-interpolate/color#interpolateLab) \- interpolate Lab colors.
- [d3.interpolateHcl](https://d3js.org/d3-interpolate/color#interpolateHcl) \- interpolate HCL colors.
- [d3.interpolateHclLong](https://d3js.org/d3-interpolate/color#interpolateHclLong) \- interpolate HCL colors, the long way.
- [d3.interpolateCubehelix](https://d3js.org/d3-interpolate/color#interpolateCubehelix) \- interpolate Cubehelix colors.
- [d3.interpolateCubehelixLong](https://d3js.org/d3-interpolate/color#interpolateCubehelixLong) \- interpolate Cubehelix colors, the long way.
- [_interpolateColor_.gamma](https://d3js.org/d3-interpolate/color#interpolateColor_gamma) \- apply gamma correction during interpolation.
- [d3.interpolateHue](https://d3js.org/d3-interpolate/color#interpolateHue) \- interpolate a hue angle.

### [Transform interpolation](https://d3js.org/d3-interpolate/transform) [​](https://d3js.org/api\#transform-interpolation)

- [d3.interpolateTransformCss](https://d3js.org/d3-interpolate/transform#interpolateTransformCss) \- interpolate 2D CSS transforms.
- [d3.interpolateTransformSvg](https://d3js.org/d3-interpolate/transform#interpolateTransformSvg) \- interpolate 2D SVG transforms.

### [Zoom interpolation](https://d3js.org/d3-interpolate/zoom) [​](https://d3js.org/api\#zoom-interpolation)

- [d3.interpolateZoom](https://d3js.org/d3-interpolate/zoom#interpolateZoom) \- zoom and pan between two views.
- [_interpolateZoom_.rho](https://d3js.org/d3-interpolate/zoom#interpolateZoom_rho) \- set the curvature _rho_ of the zoom interpolator.

## [d3-path](https://d3js.org/d3-path) [​](https://d3js.org/api\#d3-path)

Serialize Canvas path commands to SVG.

- [d3.path](https://d3js.org/d3-path#path) \- create a new path serializer.
- [_path_.moveTo](https://d3js.org/d3-path#path_moveTo) \- move to the given point.
- [_path_.closePath](https://d3js.org/d3-path#path_closePath) \- close the current subpath.
- [_path_.lineTo](https://d3js.org/d3-path#path_lineTo) \- draw a straight line segment.
- [_path_.quadraticCurveTo](https://d3js.org/d3-path#path_quadraticCurveTo) \- draw a quadratic Bézier segment.
- [_path_.bezierCurveTo](https://d3js.org/d3-path#path_bezierCurveTo) \- draw a cubic Bézier segment.
- [_path_.arcTo](https://d3js.org/d3-path#path_arcTo) \- draw a circular arc segment.
- [_path_.arc](https://d3js.org/d3-path#path_arc) \- draw a circular arc segment.
- [_path_.rect](https://d3js.org/d3-path#path_rect) \- draw a rectangle.
- [_path_.toString](https://d3js.org/d3-path#path_toString) \- serialize to an SVG path data string.
- [d3.pathRound](https://d3js.org/d3-path#pathRound) \- create a new path serializer with fixed output precision.

## [d3-polygon](https://d3js.org/d3-polygon) [​](https://d3js.org/api\#d3-polygon)

Geometric operations for two-dimensional polygons.

- [d3.polygonArea](https://d3js.org/d3-polygon#polygonArea) \- compute the area of the given polygon.
- [d3.polygonCentroid](https://d3js.org/d3-polygon#polygonCentroid) \- compute the centroid of the given polygon.
- [d3.polygonHull](https://d3js.org/d3-polygon#polygonHull) \- compute the convex hull of the given points.
- [d3.polygonContains](https://d3js.org/d3-polygon#polygonContains) \- test whether a point is inside a polygon.
- [d3.polygonLength](https://d3js.org/d3-polygon#polygonLength) \- compute the length of the given polygon’s perimeter.

## [d3-quadtree](https://d3js.org/d3-quadtree) [​](https://d3js.org/api\#d3-quadtree)

Two-dimensional recursive spatial subdivision.

- [d3.quadtree](https://d3js.org/d3-quadtree#quadtree) \- create a new, empty quadtree.
- [_quadtree_.x](https://d3js.org/d3-quadtree#quadtree_x) \- set the _x_ accessor.
- [_quadtree_.y](https://d3js.org/d3-quadtree#quadtree_y) \- set the _y_ accessor.
- [_quadtree_.extent](https://d3js.org/d3-quadtree#quadtree_extent) \- extend the quadtree to cover an extent.
- [_quadtree_.cover](https://d3js.org/d3-quadtree#quadtree_cover) \- extend the quadtree to cover a point.
- [_quadtree_.add](https://d3js.org/d3-quadtree#quadtree_add) \- add a datum to a quadtree.
- [_quadtree_.addAll](https://d3js.org/d3-quadtree#quadtree_addAll) \- add an array of data to a quadtree.
- [_quadtree_.remove](https://d3js.org/d3-quadtree#quadtree_remove) \- remove a datum from a quadtree.
- [_quadtree_.removeAll](https://d3js.org/d3-quadtree#quadtree_removeAll) \- remove an array of data from a quadtree.
- [_quadtree_.copy](https://d3js.org/d3-quadtree#quadtree_copy) \- create a copy of a quadtree.
- [_quadtree_.root](https://d3js.org/d3-quadtree#quadtree_root) \- get the quadtree’s root node.
- [_quadtree_.data](https://d3js.org/d3-quadtree#quadtree_data) \- retrieve all data from the quadtree.
- [_quadtree_.size](https://d3js.org/d3-quadtree#quadtree_size) \- count the number of data in the quadtree.
- [_quadtree_.find](https://d3js.org/d3-quadtree#quadtree_find) \- quickly find the closest datum in a quadtree.
- [_quadtree_.visit](https://d3js.org/d3-quadtree#quadtree_visit) \- selectively visit nodes in a quadtree.
- [_quadtree_.visitAfter](https://d3js.org/d3-quadtree#quadtree_visitAfter) \- visit all nodes in a quadtree.

## [d3-random](https://d3js.org/d3-random) [​](https://d3js.org/api\#d3-random)

Generate random numbers from various distributions.

- [d3.randomUniform](https://d3js.org/d3-random#randomUniform) \- from a uniform distribution.
- [d3.randomInt](https://d3js.org/d3-random#randomInt) \- from a uniform integer distribution.
- [d3.randomNormal](https://d3js.org/d3-random#randomNormal) \- from a normal distribution.
- [d3.randomLogNormal](https://d3js.org/d3-random#randomLogNormal) \- from a log-normal distribution.
- [d3.randomBates](https://d3js.org/d3-random#randomBates) \- from a Bates distribution.
- [d3.randomIrwinHall](https://d3js.org/d3-random#randomIrwinHall) \- from an Irwin–Hall distribution.
- [d3.randomExponential](https://d3js.org/d3-random#randomExponential) \- from an exponential distribution.
- [d3.randomPareto](https://d3js.org/d3-random#randomPareto) \- from a Pareto distribution.
- [d3.randomBernoulli](https://d3js.org/d3-random#randomBernoulli) \- from a Bernoulli distribution.
- [d3.randomGeometric](https://d3js.org/d3-random#randomGeometric) \- from a geometric distribution.
- [d3.randomBinomial](https://d3js.org/d3-random#randomBinomial) \- from a binomial distribution.
- [d3.randomGamma](https://d3js.org/d3-random#randomGamma) \- from a gamma distribution.
- [d3.randomBeta](https://d3js.org/d3-random#randomBeta) \- from a beta distribution.
- [d3.randomWeibull](https://d3js.org/d3-random#randomWeibull) \- from a Weibull, Gumbel or Fréchet distribution.
- [d3.randomCauchy](https://d3js.org/d3-random#randomCauchy) \- from a Cauchy distribution.
- [d3.randomLogistic](https://d3js.org/d3-random#randomLogistic) \- from a logistic distribution.
- [d3.randomPoisson](https://d3js.org/d3-random#randomPoisson) \- from a Poisson distribution.
- [_random_.source](https://d3js.org/d3-random#random_source) \- set the source of randomness.
- [d3.randomLcg](https://d3js.org/d3-random#randomLcg) \- a seeded pseudorandom number generator.

## [d3-scale](https://d3js.org/d3-scale) [​](https://d3js.org/api\#d3-scale)

Encodings that map abstract data to visual representation.

### [Linear scales](https://d3js.org/d3-scale/linear) [​](https://d3js.org/api\#linear-scales)

Map a continuous, quantitative domain to a continuous range.

- [d3.scaleLinear](https://d3js.org/d3-scale/linear#scaleLinear) \- create a quantitative linear scale.
- [_linear_](https://d3js.org/d3-scale/linear#_linear) \- compute the range value corresponding to a given domain value.
- [_linear_.invert](https://d3js.org/d3-scale/linear#linear_invert) \- compute the domain value corresponding to a given range value.
- [_linear_.domain](https://d3js.org/d3-scale/linear#linear_domain) \- set the input domain.
- [_linear_.range](https://d3js.org/d3-scale/linear#linear_range) \- set the output range.
- [_linear_.rangeRound](https://d3js.org/d3-scale/linear#linear_rangeRound) \- set the output range and enable rounding.
- [_linear_.clamp](https://d3js.org/d3-scale/linear#linear_clamp) \- enable clamping to the domain or range.
- [_linear_.unknown](https://d3js.org/d3-scale/linear#linear_unknown) \- set the output value for unknown inputs.
- [_linear_.interpolate](https://d3js.org/d3-scale/linear#linear_interpolate) \- set the output interpolator.
- [_linear_.ticks](https://d3js.org/d3-scale/linear#linear_ticks) \- compute representative values from the domain.
- [_linear_.tickFormat](https://d3js.org/d3-scale/linear#linear_tickFormat) \- format ticks for human consumption.
- [_linear_.nice](https://d3js.org/d3-scale/linear#linear_nice) \- extend the domain to nice round numbers.
- [_linear_.copy](https://d3js.org/d3-scale/linear#linear_copy) \- create a copy of this scale.
- [d3.tickFormat](https://d3js.org/d3-scale/linear#tickFormat) \- format ticks for human consumption.
- [d3.scaleIdentity](https://d3js.org/d3-scale/linear#scaleIdentity) \- creates an identity scale.
- [d3.scaleRadial](https://d3js.org/d3-scale/linear#scaleRadial) \- creates a radial scale.

### [Pow scales](https://d3js.org/d3-scale/pow) [​](https://d3js.org/api\#pow-scales)

- [d3.scalePow](https://d3js.org/d3-scale/pow#scalePow) \- create a quantitative power scale.
- [d3.scaleSqrt](https://d3js.org/d3-scale/pow#scaleSqrt) \- create a quantitative power scale with exponent 0.5.
- [_pow_.exponent](https://d3js.org/d3-scale/pow#pow_exponent) \- set the power exponent.

### [Log scales](https://d3js.org/d3-scale/log) [​](https://d3js.org/api\#log-scales)

- [d3.scaleLog](https://d3js.org/d3-scale/log#scaleLog) \- create a quantitative logarithmic scale.
- [_log_.base](https://d3js.org/d3-scale/log#log_base) \- set the logarithm base.
- [_log_.ticks](https://d3js.org/d3-scale/log#log_ticks) \- compute representative values from the domain.
- [_log_.tickFormat](https://d3js.org/d3-scale/log#log_tickFormat) \- format ticks for human consumption.
- [_log_.nice](https://d3js.org/d3-scale/log#log_nice) \- extend the domain to nice round numbers.

### [Symlog scales](https://d3js.org/d3-scale/symlog) [​](https://d3js.org/api\#symlog-scales)

- [d3.scaleSymlog](https://d3js.org/d3-scale/symlog#scaleSymlog) \- create a symmetric logarithmic scale.
- [_symlog_.constant](https://d3js.org/d3-scale/symlog#symlog_constant) \- set the constant of a symlog scale.

### [Time scales](https://d3js.org/d3-scale/time) [​](https://d3js.org/api\#time-scales)

- [d3.scaleTime](https://d3js.org/d3-scale/time#scaleTime) \- create a linear scale for time.
- [_time_.ticks](https://d3js.org/d3-scale/time#time_ticks) \- compute representative values from the domain.
- [_time_.tickFormat](https://d3js.org/d3-scale/time#time_tickFormat) \- format ticks for human consumption.
- [_time_.nice](https://d3js.org/d3-scale/time#time_nice) \- extend the domain to nice round times.
- [d3.scaleUtc](https://d3js.org/d3-scale/time#scaleUtc) \- create a linear scale for UTC.

### [Sequential scales](https://d3js.org/d3-scale/sequential) [​](https://d3js.org/api\#sequential-scales)

Map a continuous, quantitative domain to a continuous, fixed interpolator.

- [d3.scaleSequential](https://d3js.org/d3-scale/sequential#scaleSequential) \- create a sequential scale.
- [_sequential_.interpolator](https://d3js.org/d3-scale/sequential#sequential_interpolator) \- set the scale’s output interpolator.
- [_sequential_.range](https://d3js.org/d3-scale/sequential#sequential_range) \- set the output range.
- [_sequential_.rangeRound](https://d3js.org/d3-scale/sequential#sequential_rangeRound) \- set the output range and enable rounding.
- [d3.scaleSequentialLog](https://d3js.org/d3-scale/sequential#scaleSequentialLog) \- create a logarithmic sequential scale.
- [d3.scaleSequentialPow](https://d3js.org/d3-scale/sequential#scaleSequentialPow) \- create a power sequential scale.
- [d3.scaleSequentialSqrt](https://d3js.org/d3-scale/sequential#scaleSequentialSqrt) \- create a power sequential scale with exponent 0.5.
- [d3.scaleSequentialSymlog](https://d3js.org/d3-scale/sequential#scaleSequentialSymlog) \- create a symmetric logarithmic sequential scale.
- [d3.scaleSequentialQuantile](https://d3js.org/d3-scale/sequential#scaleSequentialQuantile) \- create a sequential scale using a _p_-quantile transform.
- [_sequentialQuantile_.quantiles](https://d3js.org/d3-scale/sequential#sequentialQuantile_quantiles) \- return the scale’s quantiles.

### [Diverging scales](https://d3js.org/d3-scale/diverging) [​](https://d3js.org/api\#diverging-scales)

Map a continuous, quantitative domain to a continuous, fixed interpolator.

- [d3.scaleDiverging](https://d3js.org/d3-scale/diverging#scaleDiverging) \- create a diverging scale.
- [_diverging_.interpolator](https://d3js.org/d3-scale/diverging#diverging_interpolator) \- set the scale’s output interpolator.
- [_diverging_.range](https://d3js.org/d3-scale/diverging#diverging_range) \- set the output range.
- [_diverging_.rangeRound](https://d3js.org/d3-scale/diverging#diverging_rangeRound) \- set the output range and enable rounding.
- [d3.scaleDivergingLog](https://d3js.org/d3-scale/diverging#scaleDivergingLog) \- create a diverging logarithmic scale.
- [d3.scaleDivergingPow](https://d3js.org/d3-scale/diverging#scaleDivergingPow) \- create a diverging power scale.
- [d3.scaleDivergingSqrt](https://d3js.org/d3-scale/diverging#scaleDivergingSqrt) \- create a diverging power scale with exponent 0.5.
- [d3.scaleDivergingSymlog](https://d3js.org/d3-scale/diverging#scaleDivergingSymlog) \- create a diverging symmetric logarithmic scale.

### [Quantize scales](https://d3js.org/d3-scale/quantize) [​](https://d3js.org/api\#quantize-scales)

Map a continuous, quantitative domain to a discrete range.

- [d3.scaleQuantize](https://d3js.org/d3-scale/quantize#scaleQuantize) \- create a uniform quantizing linear scale.
- [_quantize_](https://d3js.org/d3-scale/quantize#_quantize) \- compute the range value corresponding to a given domain value.
- [_quantize_.invertExtent](https://d3js.org/d3-scale/quantize#quantize_invertExtent) \- compute the domain values corresponding to a given range value.
- [_quantize_.domain](https://d3js.org/d3-scale/quantize#quantize_domain) \- set the input domain.
- [_quantize_.range](https://d3js.org/d3-scale/quantize#quantize_range) \- set the output range.
- [_quantize_.thresholds](https://d3js.org/d3-scale/quantize#quantize_thresholds) \- return the array of computed thresholds within the domain.
- [_quantize_.copy](https://d3js.org/d3-scale/quantize#quantize_copy) \- create a copy of this scale.

### [Quantile scales](https://d3js.org/d3-scale/quantile) [​](https://d3js.org/api\#quantile-scales)

- [d3.scaleQuantile](https://d3js.org/d3-scale/quantile#scaleQuantile) \- create a quantile quantizing linear scale.
- [_quantile_](https://d3js.org/d3-scale/quantile#_quantile) \- compute the range value corresponding to a given domain value.
- [_quantile_.invertExtent](https://d3js.org/d3-scale/quantile#quantile_invertExtent) \- compute the domain values corresponding to a given range value.
- [_quantile_.domain](https://d3js.org/d3-scale/quantile#quantile_domain) \- set the input domain.
- [_quantile_.range](https://d3js.org/d3-scale/quantile#quantile_range) \- set the output range.
- [_quantile_.quantiles](https://d3js.org/d3-scale/quantile#quantile_quantiles) \- get the quantile thresholds.
- [_quantile_.copy](https://d3js.org/d3-scale/quantile#quantile_copy) \- create a copy of this scale.

### [Threshold scales](https://d3js.org/d3-scale/threshold) [​](https://d3js.org/api\#threshold-scales)

- [d3.scaleThreshold](https://d3js.org/d3-scale/threshold#scaleThreshold) \- create an arbitrary quantizing linear scale.
- [_threshold_](https://d3js.org/d3-scale/threshold#_threshold) \- compute the range value corresponding to a given domain value.
- [_threshold_.invertExtent](https://d3js.org/d3-scale/threshold#threshold_invertExtent) \- compute the domain values corresponding to a given range value.
- [_threshold_.domain](https://d3js.org/d3-scale/threshold#threshold_domain) \- set the input domain.
- [_threshold_.range](https://d3js.org/d3-scale/threshold#threshold_range) \- set the output range.
- [_threshold_.copy](https://d3js.org/d3-scale/threshold#threshold_copy) \- create a copy of this scale.

### [Ordinal scales](https://d3js.org/d3-scale/ordinal) [​](https://d3js.org/api\#ordinal-scales)

Map a discrete domain to a discrete range.

- [d3.scaleOrdinal](https://d3js.org/d3-scale/ordinal#scaleOrdinal) \- create an ordinal scale.
- [_ordinal_](https://d3js.org/d3-scale/ordinal#_ordinal) \- compute the range value corresponding to a given domain value.
- [_ordinal_.domain](https://d3js.org/d3-scale/ordinal#ordinal_domain) \- set the input domain.
- [_ordinal_.range](https://d3js.org/d3-scale/ordinal#ordinal_range) \- set the output range.
- [_ordinal_.unknown](https://d3js.org/d3-scale/ordinal#ordinal_unknown) \- set the output value for unknown inputs.
- [_ordinal_.copy](https://d3js.org/d3-scale/ordinal#ordinal_copy) \- create a copy of this scale.
- [d3.scaleImplicit](https://d3js.org/d3-scale/ordinal#scaleImplicit) \- a special unknown value for implicit domains.

### [Band scales](https://d3js.org/d3-scale/band) [​](https://d3js.org/api\#band-scales)

- [d3.scaleBand](https://d3js.org/d3-scale/band#scaleBand) \- create an ordinal band scale.
- [_band_](https://d3js.org/d3-scale/band#_band) \- compute the band start corresponding to a given domain value.
- [_band_.domain](https://d3js.org/d3-scale/band#band_domain) \- set the input domain.
- [_band_.range](https://d3js.org/d3-scale/band#band_range) \- set the output range.
- [_band_.rangeRound](https://d3js.org/d3-scale/band#band_rangeRound) \- set the output range and enable rounding.
- [_band_.round](https://d3js.org/d3-scale/band#band_round) \- enable rounding.
- [_band_.paddingInner](https://d3js.org/d3-scale/band#band_paddingInner) \- set padding between bands.
- [_band_.paddingOuter](https://d3js.org/d3-scale/band#band_paddingOuter) \- set padding outside the first and last bands.
- [_band_.padding](https://d3js.org/d3-scale/band#band_padding) \- set padding outside and between bands.
- [_band_.align](https://d3js.org/d3-scale/band#band_align) \- set band alignment, if there is extra space.
- [_band_.bandwidth](https://d3js.org/d3-scale/band#band_bandwidth) \- get the width of each band.
- [_band_.step](https://d3js.org/d3-scale/band#band_step) \- get the distance between the starts of adjacent bands.
- [_band_.copy](https://d3js.org/d3-scale/band#band_copy) \- create a copy of this scale.

### [Point scales](https://d3js.org/d3-scale/point) [​](https://d3js.org/api\#point-scales)

- [d3.scalePoint](https://d3js.org/d3-scale/point#scalePoint) \- create an ordinal point scale.
- [_point_](https://d3js.org/d3-scale/point#_point) \- compute the point corresponding to a given domain value.
- [_point_.domain](https://d3js.org/d3-scale/point#point_domain) \- set the input domain.
- [_point_.range](https://d3js.org/d3-scale/point#point_range) \- set the output range.
- [_point_.rangeRound](https://d3js.org/d3-scale/point#point_rangeRound) \- set the output range and enable rounding.
- [_point_.round](https://d3js.org/d3-scale/point#point_round) \- enable rounding.
- [_point_.padding](https://d3js.org/d3-scale/point#point_padding) \- set padding outside the first and last point.
- [_point_.align](https://d3js.org/d3-scale/point#point_align) \- set point alignment, if there is extra space.
- [_point_.bandwidth](https://d3js.org/d3-scale/point#point_bandwidth) \- returns zero.
- [_point_.step](https://d3js.org/d3-scale/point#point_step) \- get the distance between the starts of adjacent points.
- [_point_.copy](https://d3js.org/d3-scale/point#point_copy) \- create a copy of this scale.

## [d3-scale-chromatic](https://d3js.org/d3-scale-chromatic) [​](https://d3js.org/api\#d3-scale-chromatic)

Color ramps and palettes for quantitative, ordinal and categorical scales.

### [Categorical](https://d3js.org/d3-scale-chromatic/categorical) [​](https://d3js.org/api\#categorical)

- [d3.schemeCategory10](https://d3js.org/d3-scale-chromatic/categorical#schemeCategory10) \- an array of ten categorical colors.
- [d3.schemeAccent](https://d3js.org/d3-scale-chromatic/categorical#schemeAccent) \- an array of eight categorical colors.
- [d3.schemeDark2](https://d3js.org/d3-scale-chromatic/categorical#schemeDark2) \- an array of eight categorical colors.
- [d3.schemeObservable10](https://d3js.org/d3-scale-chromatic/categorical#schemeObservable10) \- an array of ten categorical colors.
- [d3.schemePaired](https://d3js.org/d3-scale-chromatic/categorical#schemePaired) \- an array of twelve categorical colors.
- [d3.schemePastel1](https://d3js.org/d3-scale-chromatic/categorical#schemePastel1) \- an array of nine categorical colors.
- [d3.schemePastel2](https://d3js.org/d3-scale-chromatic/categorical#schemePastel2) \- an array of eight categorical colors.
- [d3.schemeSet1](https://d3js.org/d3-scale-chromatic/categorical#schemeSet1) \- an array of nine categorical colors.
- [d3.schemeSet2](https://d3js.org/d3-scale-chromatic/categorical#schemeSet2) \- an array of eight categorical colors.
- [d3.schemeSet3](https://d3js.org/d3-scale-chromatic/categorical#schemeSet3) \- an array of twelve categorical colors.
- [d3.schemeTableau10](https://d3js.org/d3-scale-chromatic/categorical#schemeTableau10) \- an array of ten categorical colors.

### [Cyclical](https://d3js.org/d3-scale-chromatic/cyclical) [​](https://d3js.org/api\#cyclical)

- [d3.interpolateRainbow](https://d3js.org/d3-scale-chromatic/cyclical#interpolateRainbow) \- the “less-angry” rainbow
- [d3.interpolateSinebow](https://d3js.org/d3-scale-chromatic/cyclical#interpolateSinebow) \- the “sinebow” smooth rainbow

### [Diverging](https://d3js.org/d3-scale-chromatic/diverging) [​](https://d3js.org/api\#diverging)

- [d3.interpolateBrBG](https://d3js.org/d3-scale-chromatic/diverging#interpolateBrBG) \- ColorBrewer BrBG interpolator.
- [d3.interpolatePiYG](https://d3js.org/d3-scale-chromatic/diverging#interpolatePiYG) \- ColorBrewer PiYG interpolator.
- [d3.interpolatePRGn](https://d3js.org/d3-scale-chromatic/diverging#interpolatePRGn) \- ColorBrewer PRGn interpolator.
- [d3.interpolatePuOr](https://d3js.org/d3-scale-chromatic/diverging#interpolatePuOr) \- ColorBrewer PuOr interpolator.
- [d3.interpolateRdBu](https://d3js.org/d3-scale-chromatic/diverging#interpolateRdBu) \- ColorBrewer RdBu interpolator.
- [d3.interpolateRdGy](https://d3js.org/d3-scale-chromatic/diverging#interpolateRdGy) \- ColorBrewer RdGy interpolator.
- [d3.interpolateRdYlBu](https://d3js.org/d3-scale-chromatic/diverging#interpolateRdYlBu) \- ColorBrewer RdYlBu interpolator.
- [d3.interpolateRdYlGn](https://d3js.org/d3-scale-chromatic/diverging#interpolateRdYlGn) \- ColorBrewer RdYlGn interpolator.
- [d3.interpolateSpectral](https://d3js.org/d3-scale-chromatic/diverging#interpolateSpectral) \- ColorBrewer spectral interpolator.
- [d3.schemeBrBG](https://d3js.org/d3-scale-chromatic/diverging#schemeBrBG) \- ColorBrewer BrBG scheme.
- [d3.schemePiYG](https://d3js.org/d3-scale-chromatic/diverging#schemePiYG) \- ColorBrewer PiYG scheme.
- [d3.schemePRGn](https://d3js.org/d3-scale-chromatic/diverging#schemePRGn) \- ColorBrewer PRGn scheme.
- [d3.schemePuOr](https://d3js.org/d3-scale-chromatic/diverging#schemePuOr) \- ColorBrewer PuOr scheme.
- [d3.schemeRdBu](https://d3js.org/d3-scale-chromatic/diverging#schemeRdBu) \- ColorBrewer RdBu scheme.
- [d3.schemeRdGy](https://d3js.org/d3-scale-chromatic/diverging#schemeRdGy) \- ColorBrewer RdGy scheme.
- [d3.schemeRdYlBu](https://d3js.org/d3-scale-chromatic/diverging#schemeRdYlBu) \- ColorBrewer RdYlBu scheme.
- [d3.schemeRdYlGn](https://d3js.org/d3-scale-chromatic/diverging#schemeRdYlGn) \- ColorBrewer RdYlGn scheme.
- [d3.schemeSpectral](https://d3js.org/d3-scale-chromatic/diverging#schemeSpectral) \- ColorBrewer spectral scheme.

### [Sequential](https://d3js.org/d3-scale-chromatic/sequential) [​](https://d3js.org/api\#sequential)

- [d3.interpolateBlues](https://d3js.org/d3-scale-chromatic/sequential#interpolateBlues) -
- [d3.interpolateGreens](https://d3js.org/d3-scale-chromatic/sequential#interpolateGreens) -
- [d3.interpolateGreys](https://d3js.org/d3-scale-chromatic/sequential#interpolateGreys) -
- [d3.interpolateOranges](https://d3js.org/d3-scale-chromatic/sequential#interpolateOranges) -
- [d3.interpolatePurples](https://d3js.org/d3-scale-chromatic/sequential#interpolatePurples) -
- [d3.interpolateReds](https://d3js.org/d3-scale-chromatic/sequential#interpolateReds) -
- [d3.schemeBlues](https://d3js.org/d3-scale-chromatic/sequential#schemeBlues) -
- [d3.schemeGreens](https://d3js.org/d3-scale-chromatic/sequential#schemeGreens) -
- [d3.schemeGreys](https://d3js.org/d3-scale-chromatic/sequential#schemeGreys) -
- [d3.schemeOranges](https://d3js.org/d3-scale-chromatic/sequential#schemeOranges) -
- [d3.schemePurples](https://d3js.org/d3-scale-chromatic/sequential#schemePurples) -
- [d3.schemeReds](https://d3js.org/d3-scale-chromatic/sequential#schemeReds) -
- [d3.interpolateBuGn](https://d3js.org/d3-scale-chromatic/sequential#interpolateBuGn) \- ColorBrewer BuGn interpolator.
- [d3.interpolateBuPu](https://d3js.org/d3-scale-chromatic/sequential#interpolateBuPu) \- ColorBrewer BuPu interpolator.
- [d3.interpolateCividis](https://d3js.org/d3-scale-chromatic/sequential#interpolateCividis) \- cividis interpolator.
- [d3.interpolateCool](https://d3js.org/d3-scale-chromatic/sequential#interpolateCool) \- cool interpolator.
- [d3.interpolateCubehelixDefault](https://d3js.org/d3-scale-chromatic/sequential#interpolateCubehelixDefault) \- cubehelix interpolator.
- [d3.interpolateGnBu](https://d3js.org/d3-scale-chromatic/sequential#interpolateGnBu) \- ColorBrewer GnBu interpolator.
- [d3.interpolateInferno](https://d3js.org/d3-scale-chromatic/sequential#interpolateInferno) \- inferno interpolator.
- [d3.interpolateMagma](https://d3js.org/d3-scale-chromatic/sequential#interpolateMagma) \- magma interpolator.
- [d3.interpolateOrRd](https://d3js.org/d3-scale-chromatic/sequential#interpolateOrRd) \- ColorBrewer OrRd interpolator.
- [d3.interpolatePlasma](https://d3js.org/d3-scale-chromatic/sequential#interpolatePlasma) \- plasma interpolator.
- [d3.interpolatePuBu](https://d3js.org/d3-scale-chromatic/sequential#interpolatePuBu) \- ColorBrewer PuBu interpolator.
- [d3.interpolatePuBuGn](https://d3js.org/d3-scale-chromatic/sequential#interpolatePuBuGn) \- ColorBrewer PuBuGn interpolator.
- [d3.interpolatePuRd](https://d3js.org/d3-scale-chromatic/sequential#interpolatePuRd) \- ColorBrewer PuRd interpolator.
- [d3.interpolateRdPu](https://d3js.org/d3-scale-chromatic/sequential#interpolateRdPu) \- ColorBrewer RdPu interpolator.
- [d3.interpolateTurbo](https://d3js.org/d3-scale-chromatic/sequential#interpolateTurbo) \- turbo interpolator.
- [d3.interpolateViridis](https://d3js.org/d3-scale-chromatic/sequential#interpolateViridis) \- viridis interpolator.
- [d3.interpolateWarm](https://d3js.org/d3-scale-chromatic/sequential#interpolateWarm) \- warm interpolator.
- [d3.interpolateYlGn](https://d3js.org/d3-scale-chromatic/sequential#interpolateYlGn) \- ColorBrewer YlGn interpolator.
- [d3.interpolateYlGnBu](https://d3js.org/d3-scale-chromatic/sequential#interpolateYlGnBu) \- ColorBrewer YlGnBu interpolator.
- [d3.interpolateYlOrBr](https://d3js.org/d3-scale-chromatic/sequential#interpolateYlOrBr) \- ColorBrewer YlOrBr interpolator.
- [d3.interpolateYlOrRd](https://d3js.org/d3-scale-chromatic/sequential#interpolateYlOrRd) \- ColorBrewer YlOrRd interpolator.
- [d3.schemeBuGn](https://d3js.org/d3-scale-chromatic/sequential#schemeBuGn) \- ColorBrewer BuGn scheme.
- [d3.schemeBuPu](https://d3js.org/d3-scale-chromatic/sequential#schemeBuPu) \- ColorBrewer BuPu scheme.
- [d3.schemeGnBu](https://d3js.org/d3-scale-chromatic/sequential#schemeGnBu) \- ColorBrewer GnBu scheme.
- [d3.schemeOrRd](https://d3js.org/d3-scale-chromatic/sequential#schemeOrRd) \- ColorBrewer OrRd scheme.
- [d3.schemePuBu](https://d3js.org/d3-scale-chromatic/sequential#schemePuBu) \- ColorBrewer PuBu scheme.
- [d3.schemePuBuGn](https://d3js.org/d3-scale-chromatic/sequential#schemePuBuGn) \- ColorBrewer PuBuGn scheme.
- [d3.schemePuRd](https://d3js.org/d3-scale-chromatic/sequential#schemePuRd) \- ColorBrewer PuRd scheme.
- [d3.schemeRdPu](https://d3js.org/d3-scale-chromatic/sequential#schemeRdPu) \- ColorBrewer RdPu scheme.
- [d3.schemeYlGn](https://d3js.org/d3-scale-chromatic/sequential#schemeYlGn) \- ColorBrewer YlGn scheme.
- [d3.schemeYlGnBu](https://d3js.org/d3-scale-chromatic/sequential#schemeYlGnBu) \- ColorBrewer YlGnBu scheme.
- [d3.schemeYlOrBr](https://d3js.org/d3-scale-chromatic/sequential#schemeYlOrBr) \- ColorBrewer YlOrBr scheme.
- [d3.schemeYlOrRd](https://d3js.org/d3-scale-chromatic/sequential#schemeYlOrRd) \- ColorBrewer YlOrRd scheme.

## [d3-selection](https://d3js.org/d3-selection) [​](https://d3js.org/api\#d3-selection)

Transform the DOM by selecting elements and joining to data.

### [Selecting elements](https://d3js.org/d3-selection/selecting) [​](https://d3js.org/api\#selecting-elements)

- [d3.selection](https://d3js.org/d3-selection/selecting#selection) \- select the root document element.
- [d3.select](https://d3js.org/d3-selection/selecting#select) \- select an element from the document.
- [d3.selectAll](https://d3js.org/d3-selection/selecting#selectAll) \- select multiple elements from the document.
- [_selection_.select](https://d3js.org/d3-selection/selecting#selection_select) \- select a descendant element for each selected element.
- [_selection_.selectAll](https://d3js.org/d3-selection/selecting#selection_selectAll) \- select multiple descendants for each selected element.
- [_selection_.filter](https://d3js.org/d3-selection/selecting#selection_filter) \- filter elements based on data.
- [_selection_.merge](https://d3js.org/d3-selection/joining#selection_merge) \- merge this selection with another.
- [_selection_.selectChild](https://d3js.org/d3-selection/selecting#selection_selectChild) \- select a child element for each selected element.
- [_selection_.selectChildren](https://d3js.org/d3-selection/selecting#selection_selectChildren) \- select the children elements for each selected element.
- [_selection_.selection](https://d3js.org/d3-selection/selecting#selection_selection) \- return the selection.
- [d3.matcher](https://d3js.org/d3-selection/selecting#matcher) \- test whether an element matches a selector.
- [d3.selector](https://d3js.org/d3-selection/selecting#selector) \- select an element.
- [d3.selectorAll](https://d3js.org/d3-selection/selecting#selectorAll) \- select elements.
- [d3.window](https://d3js.org/d3-selection/selecting#window) \- get a node’s owner window.
- [d3.style](https://d3js.org/d3-selection/selecting#style) \- get a node’s current style value.

### [Modifying elements](https://d3js.org/d3-selection/modifying) [​](https://d3js.org/api\#modifying-elements)

- [_selection_.attr](https://d3js.org/d3-selection/modifying#selection_attr) \- get or set an attribute.
- [_selection_.classed](https://d3js.org/d3-selection/modifying#selection_classed) \- get, add or remove CSS classes.
- [_selection_.style](https://d3js.org/d3-selection/modifying#selection_style) \- get or set a style property.
- [_selection_.property](https://d3js.org/d3-selection/modifying#selection_property) \- get or set a (raw) property.
- [_selection_.text](https://d3js.org/d3-selection/modifying#selection_text) \- get or set the text content.
- [_selection_.html](https://d3js.org/d3-selection/modifying#selection_html) \- get or set the inner HTML.
- [_selection_.append](https://d3js.org/d3-selection/modifying#selection_append) \- create, append and select new elements.
- [_selection_.insert](https://d3js.org/d3-selection/modifying#selection_insert) \- create, insert and select new elements.
- [_selection_.remove](https://d3js.org/d3-selection/modifying#selection_remove) \- remove elements from the document.
- [_selection_.clone](https://d3js.org/d3-selection/modifying#selection_clone) \- insert clones of selected elements.
- [_selection_.sort](https://d3js.org/d3-selection/modifying#selection_sort) \- sort elements in the document based on data.
- [_selection_.order](https://d3js.org/d3-selection/modifying#selection_order) \- reorders elements in the document to match the selection.
- [_selection_.raise](https://d3js.org/d3-selection/modifying#selection_raise) \- reorders each element as the last child of its parent.
- [_selection_.lower](https://d3js.org/d3-selection/modifying#selection_lower) \- reorders each element as the first child of its parent.
- [d3.create](https://d3js.org/d3-selection/modifying#create) \- create and select a detached element.
- [d3.creator](https://d3js.org/d3-selection/modifying#creator) \- create an element by name.

### [Joining data](https://d3js.org/d3-selection/joining) [​](https://d3js.org/api\#joining-data)

- [_selection_.data](https://d3js.org/d3-selection/joining#selection_data) \- bind elements to data.
- [_selection_.join](https://d3js.org/d3-selection/joining#selection_join) \- enter, update or exit elements based on data.
- [_selection_.enter](https://d3js.org/d3-selection/joining#selection_enter) \- get the enter selection (data missing elements).
- [_selection_.exit](https://d3js.org/d3-selection/joining#selection_exit) \- get the exit selection (elements missing data).
- [_selection_.datum](https://d3js.org/d3-selection/joining#selection_datum) \- get or set element data (without joining).

### [Handling events](https://d3js.org/d3-selection/events) [​](https://d3js.org/api\#handling-events)

- [_selection_.on](https://d3js.org/d3-selection/events#selection_on) \- add or remove event listeners.
- [_selection_.dispatch](https://d3js.org/d3-selection/events#selection_dispatch) \- dispatch a custom event.
- [d3.pointer](https://d3js.org/d3-selection/events#pointer) \- get the pointer’s position of an event.
- [d3.pointers](https://d3js.org/d3-selection/events#pointers) \- get the pointers’ positions of an event.

### [Control flow](https://d3js.org/d3-selection/control-flow) [​](https://d3js.org/api\#control-flow)

- [_selection_.each](https://d3js.org/d3-selection/control-flow#selection_each) \- call a function for each element.
- [_selection_.call](https://d3js.org/d3-selection/control-flow#selection_call) \- call a function with this selection.
- [_selection_.empty](https://d3js.org/d3-selection/control-flow#selection_empty) \- returns true if this selection is empty.
- [_selection_.nodes](https://d3js.org/d3-selection/control-flow#selection_nodes) \- returns an array of all selected elements.
- [_selection_.node](https://d3js.org/d3-selection/control-flow#selection_node) \- returns the first (non-null) element.
- [_selection_.size](https://d3js.org/d3-selection/control-flow#selection_size) \- returns the count of elements.
- [_selection_\[Symbol.iterator\]](https://d3js.org/d3-selection/control-flow#selection_iterator) \- iterate over the selection’s nodes.

### [Local variables](https://d3js.org/d3-selection/locals) [​](https://d3js.org/api\#local-variables)

- [d3.local](https://d3js.org/d3-selection/locals#local) \- declares a new local variable.
- [_local_.set](https://d3js.org/d3-selection/locals#local_set) \- set a local variable’s value.
- [_local_.get](https://d3js.org/d3-selection/locals#local_get) \- get a local variable’s value.
- [_local_.remove](https://d3js.org/d3-selection/locals#local_remove) \- delete a local variable.
- [_local_.toString](https://d3js.org/d3-selection/locals#local_toString) \- get the property identifier of a local variable.

### [Namespaces](https://d3js.org/d3-selection/namespaces) [​](https://d3js.org/api\#namespaces)

- [d3.namespace](https://d3js.org/d3-selection/namespaces#namespace) \- qualify a prefixed XML name, such as “xlink:href”.
- [d3.namespaces](https://d3js.org/d3-selection/namespaces#namespaces) \- the built-in XML namespaces.

## [d3-shape](https://d3js.org/d3-shape) [​](https://d3js.org/api\#d3-shape)

Graphical primitives for visualization.

### [Arcs](https://d3js.org/d3-shape/arc) [​](https://d3js.org/api\#arcs)

Circular or annular sectors, as in a pie or donut chart.

- [d3.arc](https://d3js.org/d3-shape/arc#arc) \- create a new arc generator.
- [_arc_](https://d3js.org/d3-shape/arc#_arc) \- generate an arc for the given datum.
- [_arc_.centroid](https://d3js.org/d3-shape/arc#arc_centroid) \- compute an arc’s midpoint.
- [_arc_.innerRadius](https://d3js.org/d3-shape/arc#arc_innerRadius) \- set the inner radius.
- [_arc_.outerRadius](https://d3js.org/d3-shape/arc#arc_outerRadius) \- set the outer radius.
- [_arc_.cornerRadius](https://d3js.org/d3-shape/arc#arc_cornerRadius) \- set the corner radius, for rounded corners.
- [_arc_.startAngle](https://d3js.org/d3-shape/arc#arc_startAngle) \- set the start angle.
- [_arc_.endAngle](https://d3js.org/d3-shape/arc#arc_endAngle) \- set the end angle.
- [_arc_.padAngle](https://d3js.org/d3-shape/arc#arc_padAngle) \- set the angle between adjacent arcs, for padded arcs.
- [_arc_.padRadius](https://d3js.org/d3-shape/arc#arc_padRadius) \- set the radius at which to linearize padding.
- [_arc_.context](https://d3js.org/d3-shape/arc#arc_context) \- set the rendering context.
- [_arc_.digits](https://d3js.org/d3-shape/arc#arc_digits) \- set the output precision.

### [Pies](https://d3js.org/d3-shape/pie) [​](https://d3js.org/api\#pies)

Compute the necessary angles to represent a tabular dataset as a pie or donut chart.

- [d3.pie](https://d3js.org/d3-shape/pie#pie) \- create a new pie generator.
- [_pie_](https://d3js.org/d3-shape/pie#_pie) \- compute the arc angles for the given dataset.
- [_pie_.value](https://d3js.org/d3-shape/pie#pie_value) \- set the value accessor.
- [_pie_.sort](https://d3js.org/d3-shape/pie#pie_sort) \- set the sort order comparator.
- [_pie_.sortValues](https://d3js.org/d3-shape/pie#pie_sortValues) \- set the sort order comparator.
- [_pie_.startAngle](https://d3js.org/d3-shape/pie#pie_startAngle) \- set the overall start angle.
- [_pie_.endAngle](https://d3js.org/d3-shape/pie#pie_endAngle) \- set the overall end angle.
- [_pie_.padAngle](https://d3js.org/d3-shape/pie#pie_padAngle) \- set the pad angle between adjacent arcs.

### [Lines](https://d3js.org/d3-shape/line) [​](https://d3js.org/api\#lines)

A spline or polyline, as in a line chart.

- [d3.line](https://d3js.org/d3-shape/line#line) \- create a new line generator.
- [_line_](https://d3js.org/d3-shape/line#_line) \- generate a line for the given dataset.
- [_line_.x](https://d3js.org/d3-shape/line#line_x) \- set the _x_ accessor.
- [_line_.y](https://d3js.org/d3-shape/line#line_y) \- set the _y_ accessor.
- [_line_.defined](https://d3js.org/d3-shape/line#line_defined) \- set the defined accessor.
- [_line_.curve](https://d3js.org/d3-shape/line#line_curve) \- set the curve interpolator.
- [_line_.context](https://d3js.org/d3-shape/line#line_context) \- set the rendering context.
- [_line_.digits](https://d3js.org/d3-shape/line#line_digits) \- set the output precision.
- [d3.lineRadial](https://d3js.org/d3-shape/radial-line#lineRadial) \- create a new radial line generator.
- [_lineRadial_](https://d3js.org/d3-shape/radial-line#_lineRadial) \- generate a line for the given dataset.
- [_lineRadial_.angle](https://d3js.org/d3-shape/radial-line#lineRadial_angle) \- set the angle accessor.
- [_lineRadial_.radius](https://d3js.org/d3-shape/radial-line#lineRadial_radius) \- set the radius accessor.
- [_lineRadial_.defined](https://d3js.org/d3-shape/radial-line#lineRadial_defined) \- set the defined accessor.
- [_lineRadial_.curve](https://d3js.org/d3-shape/radial-line#lineRadial_curve) \- set the curve interpolator.
- [_lineRadial_.context](https://d3js.org/d3-shape/radial-line#lineRadial_context) \- set the rendering context.

### [Areas](https://d3js.org/d3-shape/area) [​](https://d3js.org/api\#areas)

An area, defined by a bounding topline and baseline, as in an area chart.

- [d3.area](https://d3js.org/d3-shape/area#area) \- create a new area generator.
- [_area_](https://d3js.org/d3-shape/area#_area) \- generate an area for the given dataset.
- [_area_.x](https://d3js.org/d3-shape/area#area_x) \- set the _x0_ and _x1_ accessors.
- [_area_.x0](https://d3js.org/d3-shape/area#area_x0) \- set the baseline _x_ accessor.
- [_area_.x1](https://d3js.org/d3-shape/area#area_x1) \- set the topline _x_ accessor.
- [_area_.y](https://d3js.org/d3-shape/area#area_y) \- set the _y0_ and _y1_ accessors.
- [_area_.y0](https://d3js.org/d3-shape/area#area_y0) \- set the baseline _y_ accessor.
- [_area_.y1](https://d3js.org/d3-shape/area#area_y1) \- set the topline _y_ accessor.
- [_area_.defined](https://d3js.org/d3-shape/area#area_defined) \- set the defined accessor.
- [_area_.curve](https://d3js.org/d3-shape/area#area_curve) \- set the curve interpolator.
- [_area_.context](https://d3js.org/d3-shape/area#area_context) \- set the rendering context.
- [_area_.digits](https://d3js.org/d3-shape/area#area_digits) \- set the output precision.
- [_area_.lineX0](https://d3js.org/d3-shape/area#area_lineX0) \- derive a line for the left edge of an area.
- [_area_.lineY0](https://d3js.org/d3-shape/area#area_lineY0) \- derive a line for the top edge of an area.
- [_area_.lineX1](https://d3js.org/d3-shape/area#area_lineX1) \- derive a line for the right edge of an area.
- [_area_.lineY1](https://d3js.org/d3-shape/area#area_lineY1) \- derive a line for the bottom edge of an area.
- [d3.areaRadial](https://d3js.org/d3-shape/radial-area#areaRadial) \- create a new radial area generator.
- [_areaRadial_](https://d3js.org/d3-shape/radial-area#_areaRadial) \- generate an area for the given dataset.
- [_areaRadial_.angle](https://d3js.org/d3-shape/radial-area#areaRadial_angle) \- set the start and end angle accessors.
- [_areaRadial_.startAngle](https://d3js.org/d3-shape/radial-area#areaRadial_startAngle) \- set the start angle accessor.
- [_areaRadial_.endAngle](https://d3js.org/d3-shape/radial-area#areaRadial_endAngle) \- set the end angle accessor.
- [_areaRadial_.radius](https://d3js.org/d3-shape/radial-area#areaRadial_radius) \- set the inner and outer radius accessors.
- [_areaRadial_.innerRadius](https://d3js.org/d3-shape/radial-area#areaRadial_innerRadius) \- set the inner radius accessor.
- [_areaRadial_.outerRadius](https://d3js.org/d3-shape/radial-area#areaRadial_outerRadius) \- set the outer radius accessor.
- [_areaRadial_.defined](https://d3js.org/d3-shape/radial-area#areaRadial_defined) \- set the defined accessor.
- [_areaRadial_.curve](https://d3js.org/d3-shape/radial-area#areaRadial_curve) \- set the curve interpolator.
- [_areaRadial_.context](https://d3js.org/d3-shape/radial-area#areaRadial_context) \- set the rendering context.
- [_areaRadial_.lineStartAngle](https://d3js.org/d3-shape/radial-area#areaRadial_lineStartAngle) \- derive a line for the start edge of an area.
- [_areaRadial_.lineInnerRadius](https://d3js.org/d3-shape/radial-area#areaRadial_lineInnerRadius) \- derive a line for the inner edge of an area.
- [_areaRadial_.lineEndAngle](https://d3js.org/d3-shape/radial-area#areaRadial_lineEndAngle) \- derive a line for the end edge of an area.
- [_areaRadial_.lineOuterRadius](https://d3js.org/d3-shape/radial-area#areaRadial_lineOuterRadius) \- derive a line for the outer edge of an area.

### [Curves](https://d3js.org/d3-shape/curve) [​](https://d3js.org/api\#curves)

Interpolate between points to produce a continuous shape.

- [d3.curveBasis](https://d3js.org/d3-shape/curve#curveBasis) \- a cubic basis spline, repeating the end points.
- [d3.curveBasisClosed](https://d3js.org/d3-shape/curve#curveBasisClosed) \- a closed cubic basis spline.
- [d3.curveBasisOpen](https://d3js.org/d3-shape/curve#curveBasisOpen) \- a cubic basis spline.
- [d3.curveBundle](https://d3js.org/d3-shape/curve#curveBundle) \- a straightened cubic basis spline.
- [_bundle_.beta](https://d3js.org/d3-shape/curve#curveBundle_beta) \- set the bundle tension _beta_.
- [d3.curveBumpX](https://d3js.org/d3-shape/curve#curveBumpX) \- a cubic Bézier spline with horizontal tangents.
- [d3.curveBumpY](https://d3js.org/d3-shape/curve#curveBumpY) \- a cubic Bézier spline with vertical tangents.
- [d3.curveCardinal](https://d3js.org/d3-shape/curve#curveCardinal) \- a cubic cardinal spline, with one-sided difference at each end.
- [d3.curveCardinalClosed](https://d3js.org/d3-shape/curve#curveCardinalClosed) \- a closed cubic cardinal spline.
- [d3.curveCardinalOpen](https://d3js.org/d3-shape/curve#curveCardinalOpen) \- a cubic cardinal spline.
- [_cardinal_.tension](https://d3js.org/d3-shape/curve#curveCardinal_tension) \- set the cardinal spline tension.
- [d3.curveCatmullRom](https://d3js.org/d3-shape/curve#curveCatmullRom) \- a cubic Catmull–Rom spline, with one-sided difference at each end.
- [d3.curveCatmullRomClosed](https://d3js.org/d3-shape/curve#curveCatmullRomClosed) \- a closed cubic Catmull–Rom spline.
- [d3.curveCatmullRomOpen](https://d3js.org/d3-shape/curve#curveCatmullRomOpen) \- a cubic Catmull–Rom spline.
- [_catmullRom_.alpha](https://d3js.org/d3-shape/curve#curveCatmullRom_alpha) \- set the Catmull–Rom parameter _alpha_.
- [d3.curveLinear](https://d3js.org/d3-shape/curve#curveLinear) \- a polyline.
- [d3.curveLinearClosed](https://d3js.org/d3-shape/curve#curveLinearClosed) \- a closed polyline.
- [d3.curveMonotoneX](https://d3js.org/d3-shape/curve#curveMonotoneX) \- a cubic spline that, given monotonicity in _x_, preserves it in _y_.
- [d3.curveMonotoneY](https://d3js.org/d3-shape/curve#curveMonotoneY) \- a cubic spline that, given monotonicity in _y_, preserves it in _x_.
- [d3.curveNatural](https://d3js.org/d3-shape/curve#curveNatural) \- a natural cubic spline.
- [d3.curveStep](https://d3js.org/d3-shape/curve#curveStep) \- a piecewise constant function.
- [d3.curveStepAfter](https://d3js.org/d3-shape/curve#curveStepAfter) \- a piecewise constant function.
- [d3.curveStepBefore](https://d3js.org/d3-shape/curve#curveStepBefore) \- a piecewise constant function.
- [_curve_.areaStart](https://d3js.org/d3-shape/curve#curve_areaStart) \- start a new area segment.
- [_curve_.areaEnd](https://d3js.org/d3-shape/curve#curve_areaEnd) \- end the current area segment.
- [_curve_.lineStart](https://d3js.org/d3-shape/curve#curve_lineStart) \- start a new line segment.
- [_curve_.lineEnd](https://d3js.org/d3-shape/curve#curve_lineEnd) \- end the current line segment.
- [_curve_.point](https://d3js.org/d3-shape/curve#curve_point) \- add a point to the current line segment.

### [Links](https://d3js.org/d3-shape/link) [​](https://d3js.org/api\#links)

A smooth cubic Bézier curve from a source to a target.

- [d3.link](https://d3js.org/d3-shape/link#link) \- create a new link generator.
- [d3.linkVertical](https://d3js.org/d3-shape/link#linkVertical) \- create a new vertical link generator.
- [d3.linkHorizontal](https://d3js.org/d3-shape/link#linkHorizontal) \- create a new horizontal link generator.
- [_link_](https://d3js.org/d3-shape/link#_link) \- generate a link.
- [_link_.source](https://d3js.org/d3-shape/link#link_source) \- set the source accessor.
- [_link_.target](https://d3js.org/d3-shape/link#link_target) \- set the target accessor.
- [_link_.x](https://d3js.org/d3-shape/link#link_x) \- set the point _x_-accessor.
- [_link_.y](https://d3js.org/d3-shape/link#link_y) \- set the point _y_-accessor.
- [_link_.context](https://d3js.org/d3-shape/link#link_context) \- set the rendering context.
- [_link_.digits](https://d3js.org/d3-shape/link#link_digits) \- set the output precision.
- [d3.linkRadial](https://d3js.org/d3-shape/radial-link#linkRadial) \- create a new radial link generator.
- [_linkRadial_.angle](https://d3js.org/d3-shape/radial-link#linkRadial_angle) \- set the point _angle_ accessor.
- [_linkRadial_.radius](https://d3js.org/d3-shape/radial-link#linkRadial_radius) \- set the point _radius_ accessor.

### [Symbols](https://d3js.org/d3-shape/symbol) [​](https://d3js.org/api\#symbols)

A categorical shape encoding, as in a scatterplot.

- [d3.symbol](https://d3js.org/d3-shape/symbol#symbol) \- create a new symbol generator.
- [_symbol_](https://d3js.org/d3-shape/symbol#_symbol) \- generate a symbol for the given datum.
- [_symbol_.type](https://d3js.org/d3-shape/symbol#symbol_type) \- set the symbol type.
- [_symbol_.size](https://d3js.org/d3-shape/symbol#symbol_size) \- set the size of the symbol in square pixels.
- [_symbol_.context](https://d3js.org/d3-shape/symbol#symbol_context) \- set the rendering context.
- [_symbol_.digits](https://d3js.org/d3-shape/symbol#symbol_digits) \- set the output precision.
- [d3.symbolsFill](https://d3js.org/d3-shape/symbol#symbolsFill) \- an array of built-in symbol types for filling.
- [d3.symbolsStroke](https://d3js.org/d3-shape/symbol#symbolsStroke) \- an array of built-in symbol types for stroking.
- [d3.symbolAsterisk](https://d3js.org/d3-shape/symbol#symbolAsterisk) \- an asterisk; for stroke.
- [d3.symbolCircle](https://d3js.org/d3-shape/symbol#symbolCircle) \- a circle; for fill or stroke.
- [d3.symbolCross](https://d3js.org/d3-shape/symbol#symbolCross) \- a Greek cross with arms of equal length; for fill.
- [d3.symbolDiamond](https://d3js.org/d3-shape/symbol#symbolDiamond) \- a rhombus; for fill.
- [d3.symbolDiamond2](https://d3js.org/d3-shape/symbol#symbolDiamond2) \- a rotated square; for stroke.
- [d3.symbolPlus](https://d3js.org/d3-shape/symbol#symbolPlus) \- a plus sign; for stroke.
- [d3.symbolSquare](https://d3js.org/d3-shape/symbol#symbolSquare) \- a square; for fill.
- [d3.symbolSquare2](https://d3js.org/d3-shape/symbol#symbolSquare2) \- a square; for stroke.
- [d3.symbolStar](https://d3js.org/d3-shape/symbol#symbolStar) \- a pentagonal star (pentagram); for fill.
- [d3.symbolTriangle](https://d3js.org/d3-shape/symbol#symbolTriangle) \- an up-pointing triangle; for fill.
- [d3.symbolTriangle2](https://d3js.org/d3-shape/symbol#symbolTriangle2) \- an up-pointing triangle; for stroke.
- [d3.symbolWye](https://d3js.org/d3-shape/symbol#symbolWye) \- a Y shape; for fill.
- [d3.pointRadial](https://d3js.org/d3-shape/symbol#pointRadial) \- relative coordinates of a point given an angle and radius.
- [_symbolType_.draw](https://d3js.org/d3-shape/symbol#symbolType_draw) \- draw this symbol to the given context.

### [Stacks](https://d3js.org/d3-shape/stack) [​](https://d3js.org/api\#stacks)

Stack shapes, placing one adjacent to another, as in a stacked bar chart.

- [d3.stack](https://d3js.org/d3-shape/stack#stack) \- create a new stack generator.
- [_stack_](https://d3js.org/d3-shape/stack#_stack) \- generate a stack for the given dataset.
- [_stack_.keys](https://d3js.org/d3-shape/stack#stack_keys) \- set the keys accessor.
- [_stack_.value](https://d3js.org/d3-shape/stack#stack_value) \- set the value accessor.
- [_stack_.order](https://d3js.org/d3-shape/stack#stack_order) \- set the order accessor.
- [_stack_.offset](https://d3js.org/d3-shape/stack#stack_offset) \- set the offset accessor.
- [d3.stackOrderAppearance](https://d3js.org/d3-shape/stack#stackOrderAppearance) \- put the earliest series on bottom.
- [d3.stackOrderAscending](https://d3js.org/d3-shape/stack#stackOrderAscending) \- put the smallest series on bottom.
- [d3.stackOrderDescending](https://d3js.org/d3-shape/stack#stackOrderDescending) \- put the largest series on bottom.
- [d3.stackOrderInsideOut](https://d3js.org/d3-shape/stack#stackOrderInsideOut) \- put earlier series in the middle.
- [d3.stackOrderNone](https://d3js.org/d3-shape/stack#stackOrderNone) \- use the given series order.
- [d3.stackOrderReverse](https://d3js.org/d3-shape/stack#stackOrderReverse) \- use the reverse of the given series order.
- [d3.stackOffsetExpand](https://d3js.org/d3-shape/stack#stackOffsetExpand) \- normalize the baseline to zero and topline to one.
- [d3.stackOffsetDiverging](https://d3js.org/d3-shape/stack#stackOffsetDiverging) \- positive above zero; negative below zero.
- [d3.stackOffsetNone](https://d3js.org/d3-shape/stack#stackOffsetNone) \- apply a zero baseline.
- [d3.stackOffsetSilhouette](https://d3js.org/d3-shape/stack#stackOffsetSilhouette) \- center the streamgraph around zero.
- [d3.stackOffsetWiggle](https://d3js.org/d3-shape/stack#stackOffsetWiggle) \- minimize streamgraph wiggling.

## [d3-time](https://d3js.org/d3-time) [​](https://d3js.org/api\#d3-time)

A calculator for humanity’s peculiar conventions of time.

- [d3.timeInterval](https://d3js.org/d3-time#timeInterval) \- implement a new custom time interval.
- [_interval_](https://d3js.org/d3-time#_interval) \- alias for _interval_.floor.
- [_interval_.floor](https://d3js.org/d3-time#interval_floor) \- round down to the nearest boundary.
- [_interval_.round](https://d3js.org/d3-time#interval_round) \- round to the nearest boundary.
- [_interval_.ceil](https://d3js.org/d3-time#interval_ceil) \- round up to the nearest boundary.
- [_interval_.offset](https://d3js.org/d3-time#interval_offset) \- offset a date by some number of intervals.
- [_interval_.range](https://d3js.org/d3-time#interval_range) \- generate a range of dates at interval boundaries.
- [_interval_.filter](https://d3js.org/d3-time#interval_filter) \- create a filtered subset of this interval.
- [_interval_.every](https://d3js.org/d3-time#interval_every) \- create a filtered subset of this interval.
- [_interval_.count](https://d3js.org/d3-time#interval_count) \- count interval boundaries between two dates.
- [d3.timeMillisecond](https://d3js.org/d3-time#timeMillisecond) \- the millisecond interval, local time.
- [d3.timeSecond](https://d3js.org/d3-time#timeSecond) \- the second interval, local time.
- [d3.timeMinute](https://d3js.org/d3-time#timeMinute) \- the minute interval, local time.
- [d3.timeHour](https://d3js.org/d3-time#timeHour) \- the hour interval, local time.
- [d3.timeDay](https://d3js.org/d3-time#timeDay) \- the day interval, local time.
- [d3.timeWeek](https://d3js.org/d3-time#timeWeek) \- the Sunday-based week interval, local time.
- [d3.timeSunday](https://d3js.org/d3-time#timeSunday) \- the Sunday-based week interval, local time.
- [d3.timeMonday](https://d3js.org/d3-time#timeMonday) \- the Monday-based week interval, local time.
- [d3.timeTuesday](https://d3js.org/d3-time#timeTuesday) \- the Tuesday-based week interval, local time.
- [d3.timeWednesday](https://d3js.org/d3-time#timeWednesday) \- the Wednesday-based week interval, local time.
- [d3.timeThursday](https://d3js.org/d3-time#timeThursday) \- the Thursday-based week interval, local time.
- [d3.timeFriday](https://d3js.org/d3-time#timeFriday) \- the Friday-based week interval, local time.
- [d3.timeSaturday](https://d3js.org/d3-time#timeSaturday) \- the Saturday-based week interval, local time.
- [d3.timeMonth](https://d3js.org/d3-time#timeMonth) \- the month interval, local time.
- [d3.timeYear](https://d3js.org/d3-time#timeYear) \- the year interval, local time.
- [d3.utcMillisecond](https://d3js.org/d3-time#timeMillisecond) \- the millisecond interval, UTC time.
- [d3.utcSecond](https://d3js.org/d3-time#timeSecond) \- the second interval, UTC time.
- [d3.utcMinute](https://d3js.org/d3-time#timeMinute) \- the minute interval, UTC time.
- [d3.utcHour](https://d3js.org/d3-time#timeHour) \- the hour interval, UTC time.
- [d3.utcDay](https://d3js.org/d3-time#timeDay) \- the day interval, UTC time.
- [d3.utcWeek](https://d3js.org/d3-time#timeWeek) \- the Sunday-based week interval, UTC time.
- [d3.utcSunday](https://d3js.org/d3-time#timeSunday) \- the Sunday-based week interval, UTC time.
- [d3.utcMonday](https://d3js.org/d3-time#timeMonday) \- the Monday-based week interval, UTC time.
- [d3.utcTuesday](https://d3js.org/d3-time#timeTuesday) \- the Tuesday-based week interval, UTC time.
- [d3.utcWednesday](https://d3js.org/d3-time#timeWednesday) \- the Wednesday-based week interval, UTC time.
- [d3.utcThursday](https://d3js.org/d3-time#timeThursday) \- the Thursday-based week interval, UTC time.
- [d3.utcFriday](https://d3js.org/d3-time#timeFriday) \- the Friday-based week interval, UTC time.
- [d3.utcSaturday](https://d3js.org/d3-time#timeSaturday) \- the Saturday-based week interval, UTC time.
- [d3.utcMonth](https://d3js.org/d3-time#timeMonth) \- the month interval, UTC time.
- [d3.utcYear](https://d3js.org/d3-time#timeYear) \- the year interval, UTC time.
- [d3.unixDay](https://d3js.org/d3-time#timeDay) \- the day interval, UTC time, not month-aligned.
- [d3.timeMilliseconds](https://d3js.org/d3-time#timeMilliseconds) \- alias for d3.timeMillisecond.range.
- [d3.timeSeconds](https://d3js.org/d3-time#timeSeconds) \- alias for d3.timeSecond.range.
- [d3.timeMinutes](https://d3js.org/d3-time#timeMinutes) \- alias for d3.timeMinute.range.
- [d3.timeHours](https://d3js.org/d3-time#timeHours) \- alias for d3.timeHour.range.
- [d3.timeDays](https://d3js.org/d3-time#timeDay) \- alias for d3.timeDay.range.
- [d3.timeWeeks](https://d3js.org/d3-time#timeWeek) \- alias for d3.timeWeek.range.
- [d3.timeSundays](https://d3js.org/d3-time#timeSunday) \- alias for d3.timeSunday.range.
- [d3.timeMondays](https://d3js.org/d3-time#timeMonday) \- alias for d3.timeMonday.range.
- [d3.timeTuesdays](https://d3js.org/d3-time#timeTuesday) \- alias for d3.timeTuesday.range.
- [d3.timeWednesdays](https://d3js.org/d3-time#timeWednesday) \- alias for d3.timeWednesday.range.
- [d3.timeThursdays](https://d3js.org/d3-time#timeThursday) \- alias for d3.timeThursday.range.
- [d3.timeFridays](https://d3js.org/d3-time#timeFriday) \- alias for d3.timeFriday.range.
- [d3.timeSaturdays](https://d3js.org/d3-time#timeSaturday) \- alias for d3.timeSaturday.range.
- [d3.timeMonths](https://d3js.org/d3-time#timeMonth) \- alias for d3.timeMonth.range.
- [d3.timeYears](https://d3js.org/d3-time#timeYear) \- alias for d3.timeYear.range.
- [d3.utcMilliseconds](https://d3js.org/d3-time#timeMillisecond) \- alias for d3.utcMillisecond.range.
- [d3.utcSeconds](https://d3js.org/d3-time#timeSecond) \- alias for d3.utcSecond.range.
- [d3.utcMinutes](https://d3js.org/d3-time#timeMinute) \- alias for d3.utcMinute.range.
- [d3.utcHours](https://d3js.org/d3-time#timeHour) \- alias for d3.utcHour.range.
- [d3.utcDays](https://d3js.org/d3-time#timeDay) \- alias for d3.utcDay.range.
- [d3.utcWeeks](https://d3js.org/d3-time#timeWeek) \- alias for d3.utcWeek.range.
- [d3.utcSundays](https://d3js.org/d3-time#timeSunday) \- alias for d3.utcSunday.range.
- [d3.utcMondays](https://d3js.org/d3-time#timeMonday) \- alias for d3.utcMonday.range.
- [d3.utcTuesdays](https://d3js.org/d3-time#timeTuesday) \- alias for d3.utcTuesday.range.
- [d3.utcWednesdays](https://d3js.org/d3-time#timeWednesday) \- alias for d3.utcWednesday.range.
- [d3.utcThursdays](https://d3js.org/d3-time#timeThursday) \- alias for d3.utcThursday.range.
- [d3.utcFridays](https://d3js.org/d3-time#timeFriday) \- alias for d3.utcFriday.range.
- [d3.utcSaturdays](https://d3js.org/d3-time#timeSaturday) \- alias for d3.utcSaturday.range.
- [d3.utcMonths](https://d3js.org/d3-time#timeMonth) \- alias for d3.utcMonth.range.
- [d3.utcYears](https://d3js.org/d3-time#timeYear) \- alias for d3.utcYear.range.
- [d3.unixDays](https://d3js.org/d3-time#timeDay) \- alias for d3.unixDay.range.
- [d3.timeTicks](https://d3js.org/d3-time#timeTicks) \- generate representative values from a time interval.
- [d3.utcTicks](https://d3js.org/d3-time#utcTicks) \- generate representative values from a time interval.
- [d3.timeTickInterval](https://d3js.org/d3-time#timeTickInterval) \- generate representative values from a time interval.
- [d3.utcTickInterval](https://d3js.org/d3-time#utcTickInterval) \- generate representative values from a time interval.

## [d3-time-format](https://d3js.org/d3-time-format) [​](https://d3js.org/api\#d3-time-format)

Parse and format times, inspired by strptime and strftime.

- [d3.timeFormat](https://d3js.org/d3-time-format#timeFormat) \- alias for _locale_.format on the default locale.
- [d3.timeParse](https://d3js.org/d3-time-format#timeParse) \- alias for _locale_.parse on the default locale.
- [d3.utcFormat](https://d3js.org/d3-time-format#utcFormat) \- alias for _locale_.utcFormat on the default locale.
- [d3.utcParse](https://d3js.org/d3-time-format#utcParse) \- alias for _locale_.utcParse on the default locale.
- [d3.isoFormat](https://d3js.org/d3-time-format#isoFormat) \- an ISO 8601 UTC formatter.
- [d3.isoParse](https://d3js.org/d3-time-format#isoParse) \- an ISO 8601 UTC parser.
- [_locale_.format](https://d3js.org/d3-time-format#locale_format) \- create a time formatter.
- [_locale_.parse](https://d3js.org/d3-time-format#locale_parse) \- create a time parser.
- [_locale_.utcFormat](https://d3js.org/d3-time-format#locale_utcFormat) \- create a UTC formatter.
- [_locale_.utcParse](https://d3js.org/d3-time-format#locale_utcParse) \- create a UTC parser.
- [d3.timeFormatLocale](https://d3js.org/d3-time-format#timeFormatLocale) \- define a custom locale.
- [d3.timeFormatDefaultLocale](https://d3js.org/d3-time-format#timeFormatDefaultLocale) \- define the default locale.

## [d3-timer](https://d3js.org/d3-timer) [​](https://d3js.org/api\#d3-timer)

An efficient queue for managing thousands of concurrent animations.

- [d3.now](https://d3js.org/d3-timer#now) \- get the current high-resolution time.
- [d3.timer](https://d3js.org/d3-timer#timer) \- schedule a new timer.
- [_timer_.restart](https://d3js.org/d3-timer#timer_restart) \- reset the timer’s start time and callback.
- [_timer_.stop](https://d3js.org/d3-timer#timer_stop) \- stop the timer.
- [d3.timerFlush](https://d3js.org/d3-timer#timerFlush) \- immediately execute any eligible timers.
- [d3.timeout](https://d3js.org/d3-timer#timeout) \- schedule a timer that stops on its first callback.
- [d3.interval](https://d3js.org/d3-timer#interval) \- schedule a timer that is called with a configurable period.

## [d3-transition](https://d3js.org/d3-transition) [​](https://d3js.org/api\#d3-transition)

Animated transitions for [selections](https://d3js.org/d3-selection).

- [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition) \- schedule a transition for the selected elements.
- [_selection_.interrupt](https://d3js.org/d3-transition/control-flow#selection_interrupt) \- interrupt and cancel transitions on the selected elements.
- [d3.interrupt](https://d3js.org/d3-transition/control-flow#interrupt) \- interrupt the active transition for a given node.
- [d3.transition](https://d3js.org/d3-transition/selecting#transition) \- schedule a transition on the root document element.
- [_transition_.select](https://d3js.org/d3-transition/selecting#transition_select) \- schedule a transition on the selected elements.
- [_transition_.selectAll](https://d3js.org/d3-transition/selecting#transition_selectAll) \- schedule a transition on the selected elements.
- [_transition_.selectChild](https://d3js.org/d3-transition/selecting#transition_selectChild) \- select a child element for each selected element.
- [_transition_.selectChildren](https://d3js.org/d3-transition/selecting#transition_selectChildren) \- select the children elements for each selected element.
- [_transition_.selection](https://d3js.org/d3-transition/selecting#transition_selection) \- returns a selection for this transition.
- [_transition_.filter](https://d3js.org/d3-transition/selecting#transition_filter) \- filter elements based on data.
- [_transition_.merge](https://d3js.org/d3-transition/selecting#transition_merge) \- merge this transition with another.
- [_transition_.transition](https://d3js.org/d3-transition/selecting#transition_transition) \- schedule a new transition following this one.
- [d3.active](https://d3js.org/d3-transition/selecting#active) \- select the active transition for a given node.
- [_transition_.attr](https://d3js.org/d3-transition/modifying#transition_attr) \- tween the given attribute using the default interpolator.
- [_transition_.attrTween](https://d3js.org/d3-transition/modifying#transition_attrTween) \- tween the given attribute using a custom interpolator.
- [_transition_.style](https://d3js.org/d3-transition/modifying#transition_style) \- tween the given style property using the default interpolator.
- [_transition_.styleTween](https://d3js.org/d3-transition/modifying#transition_styleTween) \- tween the given style property using a custom interpolator.
- [_transition_.text](https://d3js.org/d3-transition/modifying#transition_text) \- set the text content when the transition starts.
- [_transition_.textTween](https://d3js.org/d3-transition/modifying#transition_textTween) \- tween the text using a custom interpolator.
- [_transition_.remove](https://d3js.org/d3-transition/modifying#transition_remove) \- remove the selected elements when the transition ends.
- [_transition_.tween](https://d3js.org/d3-transition/modifying#transition_tween) \- run custom code during the transition.
- [_transition_.delay](https://d3js.org/d3-transition/timing#transition_delay) \- specify per-element delay in milliseconds.
- [_transition_.duration](https://d3js.org/d3-transition/timing#transition_duration) \- specify per-element duration in milliseconds.
- [_transition_.ease](https://d3js.org/d3-transition/timing#transition_ease) \- specify the easing function.
- [_transition_.easeVarying](https://d3js.org/d3-transition/timing#transition_easeVarying) \- specify an easing function factory.
- [_transition_.end](https://d3js.org/d3-transition/control-flow#transition_end) \- a promise that resolves when a transition ends.
- [_transition_.on](https://d3js.org/d3-transition/control-flow#transition_on) \- await the end of a transition.
- [_transition_.each](https://d3js.org/d3-transition/control-flow#transition_each) \- call a function for each element.
- [_transition_.call](https://d3js.org/d3-transition/control-flow#transition_call) \- call a function with this transition.
- [_transition_.empty](https://d3js.org/d3-transition/control-flow#transition_empty) \- returns true if this transition is empty.
- [_transition_.nodes](https://d3js.org/d3-transition/control-flow#transition_nodes) \- returns an array of all selected elements.
- [_transition_.node](https://d3js.org/d3-transition/control-flow#transition_node) \- returns the first (non-null) element.
- [_transition_.size](https://d3js.org/d3-transition/control-flow#transition_size) \- returns the count of elements.

## [d3-zoom](https://d3js.org/d3-zoom) [​](https://d3js.org/api\#d3-zoom)

Pan and zoom SVG, HTML or Canvas using mouse or touch input.

- [d3.zoom](https://d3js.org/d3-zoom#zoom) \- create a zoom behavior.
- [_zoom_](https://d3js.org/d3-zoom#_zoom) \- apply the zoom behavior to the selected elements.
- [_zoom_.transform](https://d3js.org/d3-zoom#zoom_transform) \- change the transform for the selected elements.
- [_zoom_.translateBy](https://d3js.org/d3-zoom#zoom_translateBy) \- translate the transform for the selected elements.
- [_zoom_.translateTo](https://d3js.org/d3-zoom#zoom_translateTo) \- translate the transform for the selected elements.
- [_zoom_.scaleBy](https://d3js.org/d3-zoom#zoom_scaleBy) \- scale the transform for the selected elements.
- [_zoom_.scaleTo](https://d3js.org/d3-zoom#zoom_scaleTo) \- scale the transform for the selected elements.
- [_zoom_.constrain](https://d3js.org/d3-zoom#zoom_constrain) \- override the transform constraint logic.
- [_zoom_.filter](https://d3js.org/d3-zoom#zoom_filter) \- control which input events initiate zooming.
- [_zoom_.touchable](https://d3js.org/d3-zoom#zoom_touchable) \- set the touch support detector.
- [_zoom_.wheelDelta](https://d3js.org/d3-zoom#zoom_wheelDelta) \- override scaling for wheel events.
- [_zoom_.extent](https://d3js.org/d3-zoom#zoom_extent) \- set the extent of the viewport.
- [_zoom_.scaleExtent](https://d3js.org/d3-zoom#zoom_scaleExtent) \- set the allowed scale range.
- [_zoom_.translateExtent](https://d3js.org/d3-zoom#zoom_translateExtent) \- set the extent of the zoomable world.
- [_zoom_.clickDistance](https://d3js.org/d3-zoom#zoom_clickDistance) \- set the click distance threshold.
- [_zoom_.tapDistance](https://d3js.org/d3-zoom#zoom_tapDistance) \- set the tap distance threshold.
- [_zoom_.duration](https://d3js.org/d3-zoom#zoom_duration) \- set the duration of zoom transitions.
- [_zoom_.interpolate](https://d3js.org/d3-zoom#zoom_interpolate) \- control the interpolation of zoom transitions.
- [_zoom_.on](https://d3js.org/d3-zoom#zoom_on) \- listen for zoom events.
- [d3.zoomTransform](https://d3js.org/d3-zoom#zoomTransform) \- get the zoom transform for a given element.
- [_transform_.scale](https://d3js.org/d3-zoom#transform_scale) \- scale a transform by the specified amount.
- [_transform_.translate](https://d3js.org/d3-zoom#transform_translate) \- translate a transform by the specified amount.
- [_transform_.apply](https://d3js.org/d3-zoom#transform_apply) \- apply the transform to the given point.
- [_transform_.applyX](https://d3js.org/d3-zoom#transform_applyX) \- apply the transform to the given _x_-coordinate.
- [_transform_.applyY](https://d3js.org/d3-zoom#transform_applyY) \- apply the transform to the given y coordinate.
- [_transform_.invert](https://d3js.org/d3-zoom#transform_invert) \- unapply the transform to the given point.
- [_transform_.invertX](https://d3js.org/d3-zoom#transform_invertX) \- unapply the transform to the given _x_-coordinate.
- [_transform_.invertY](https://d3js.org/d3-zoom#transform_invertY) \- unapply the transform to the given y coordinate.
- [_transform_.rescaleX](https://d3js.org/d3-zoom#transform_rescaleX) \- apply the transform to an x scale’s domain.
- [_transform_.rescaleY](https://d3js.org/d3-zoom#transform_rescaleY) \- apply the transform to a y scale’s domain.
- [_transform_.toString](https://d3js.org/d3-zoom#transform_toString) \- format the transform as an SVG transform string.
- [d3.zoomIdentity](https://d3js.org/d3-zoom#zoomIdentity) \- the identity transform.

## D3.js Geo Projections
[Skip to content](https://d3js.org/d3-geo#VPContent)

Return to top

# d3-geo [​](https://d3js.org/d3-geo\#d3-geo)

Map projections are sometimes implemented as point transformations: a function that takes a given longitude _lambda_ and latitude _phi_, and returns the corresponding _xy_ position on the plane. For instance, here is the spherical Mercator projection (in radians):

js

```
function mercator(lambda, phi) {
  const x = lambda;
  const y = Math.log(Math.tan(Math.PI / 4 + phi / 2));
  return [x, y];
}
```

This is a reasonable approach if your geometry consists only of points. But what about discrete geometry such as polygons and polylines?

Discrete geometry introduces new challenges when projecting from the sphere to the plane. The edges of a spherical polygon are [geodesics](https://en.wikipedia.org/wiki/Geodesic) (segments of great circles), not straight lines. Geodesics become curves in all map projections except [gnomonic](https://d3js.org/d3-geo/azimuthal#geoGnomonic), and thus accurate projection requires interpolation along each arc. D3 uses [adaptive sampling](https://observablehq.com/@d3/adaptive-sampling) inspired by [Visvalingam’s line simplification method](https://bost.ocks.org/mike/simplify/) to balance accuracy and performance.

The projection of polygons and polylines must also deal with the topological differences between the sphere and the plane. Some projections require cutting geometry that [crosses the antimeridian](https://observablehq.com/@d3/antimeridian-cutting), while others require [clipping geometry to a great circle](https://observablehq.com/@d3/orthographic-shading). Spherical polygons also require a [winding order convention](https://observablehq.com/@d3/winding-order) to determine which side of the polygon is the inside: the exterior ring for polygons smaller than a hemisphere must be clockwise, while the exterior ring for polygons [larger than a hemisphere](https://observablehq.com/@d3/oceans) must be anticlockwise. Interior rings representing holes must use the opposite winding order of their exterior ring.

D3 uses spherical [GeoJSON](http://geojson.org/geojson-spec.html) to represent geographic features in JavaScript. D3 supports a wide variety of [common](https://d3js.org/d3-geo/projection) and [unusual](https://github.com/d3/d3-geo-projection) map projections. And because D3 uses spherical geometry to represent data, you can apply any aspect to any projection by rotating geometry.

See one of:

- [Paths](https://d3js.org/d3-geo/path) \- generate SVG path data from GeoJSON
- [Projections](https://d3js.org/d3-geo/projection) \- project spherical geometry to the plane
- [Streams](https://d3js.org/d3-geo/stream) \- transform (either spherical or planar) geometry
- [Shapes](https://d3js.org/d3-geo/shape) \- generate circles, lines, and other spherical geometry
- [Spherical math](https://d3js.org/d3-geo/math) \- low-level methods for spherical geometry

TIP

To convert shapefiles to GeoJSON, use [shp2json](https://github.com/mbostock/shapefile/blob/main/README.md#shp2json), part of the [shapefile package](https://github.com/mbostock/shapefile). See [Command-Line Cartography](https://medium.com/@mbostock/command-line-cartography-part-1-897aa8f8ca2c) for an introduction to d3-geo and related tools. See also [TopoJSON](https://github.com/topojson), an extension of GeoJSON that is significantly more compact and encodes topology.

CAUTION

D3’s winding order convention is also used by [TopoJSON](https://github.com/topojson) and [ESRI shapefiles](https://github.com/mbostock/shapefile); however, it is the opposite convention of GeoJSON’s [RFC 7946](https://tools.ietf.org/html/rfc7946#section-3.1.6). Also note that standard GeoJSON WGS84 uses planar equirectangular coordinates, not spherical coordinates, and thus may require [stitching](https://github.com/d3/d3-geo-projection/blob/main/README.md#geostitch) to remove antimeridian cuts.

## Radial Area Generator
[Skip to content](https://d3js.org/d3-shape/radial-area#VPContent)

On this page

# Radial areas [​](https://d3js.org/d3-shape/radial-area\#radial-areas)

[Examples](https://observablehq.com/@d3/radial-area-chart) · A radial area generator is like the Cartesian [area generator](https://d3js.org/d3-shape/area) except the [x](https://d3js.org/d3-shape/area#area_x) and [y](https://d3js.org/d3-shape/area#area_y) accessors are replaced with [angle](https://d3js.org/d3-shape/radial-area#areaRadial_angle) and [radius](https://d3js.org/d3-shape/radial-area#areaRadial_radius) accessors. Radial areas are positioned relative to the origin; use a [transform](http://www.w3.org/TR/SVG/coords.html#TransformAttribute) to change the origin.

## areaRadial() [​](https://d3js.org/d3-shape/radial-area\#areaRadial)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Constructs a new radial area generator with the default settings.

js

```
const area = d3.areaRadial();
```

## _areaRadial_( _data_) [​](https://d3js.org/d3-shape/radial-area\#_areaRadial)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Equivalent to [_area_](https://d3js.org/d3-shape/area#_area).

js

```
svg.append("path").attr("d", area(data));
```

## _areaRadial_.angle( _angle_) [​](https://d3js.org/d3-shape/radial-area\#areaRadial_angle)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Equivalent to [_area_.x](https://d3js.org/d3-shape/area#area_x), except the accessor returns the angle in radians, with 0 at - _y_ (12 o’clock).

js

```
const area = d3.areaRadial().angle((d) => a(d.Date));
```

## _areaRadial_.startAngle( _angle_) [​](https://d3js.org/d3-shape/radial-area\#areaRadial_startAngle)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Equivalent to [_area_.x0](https://d3js.org/d3-shape/area#area_x0), except the accessor returns the angle in radians, with 0 at - _y_ (12 o’clock). Note: typically [angle](https://d3js.org/d3-shape/radial-area#areaRadial_angle) is used instead of setting separate start and end angles.

## _areaRadial_.endAngle( _angle_) [​](https://d3js.org/d3-shape/radial-area\#areaRadial_endAngle)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Equivalent to [_area_.x1](https://d3js.org/d3-shape/area#area_x1), except the accessor returns the angle in radians, with 0 at - _y_ (12 o’clock). Note: typically [angle](https://d3js.org/d3-shape/radial-area#areaRadial_angle) is used instead of setting separate start and end angles.

## _areaRadial_.radius( _radius_) [​](https://d3js.org/d3-shape/radial-area\#areaRadial_radius)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Equivalent to [_area_.y](https://d3js.org/d3-shape/area#area_y), except the accessor returns the radius: the distance from the origin.

js

```
const area = d3.areaRadial().radius((d) => r(d.temperature));
```

## _areaRadial_.innerRadius( _radius_) [​](https://d3js.org/d3-shape/radial-area\#areaRadial_innerRadius)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Equivalent to [_area_.y0](https://d3js.org/d3-shape/area#area_y0), except the accessor returns the radius: the distance from the origin.

js

```
const area = d3.areaRadial().radius((d) => r(d.low));
```

## _areaRadial_.outerRadius( _radius_) [​](https://d3js.org/d3-shape/radial-area\#areaRadial_outerRadius)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Equivalent to [_area_.y1](https://d3js.org/d3-shape/area#area_y1), except the accessor returns the radius: the distance from the origin.

js

```
const area = d3.areaRadial().radius((d) => r(d.high));
```

## _areaRadial_.defined( _defined_) [​](https://d3js.org/d3-shape/radial-area\#areaRadial_defined)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Equivalent to [_area_.defined](https://d3js.org/d3-shape/area#area_defined).

js

```
const area = d3.areaRadial().defined((d) => !isNaN(d.temperature));
```

## _areaRadial_.curve( _curve_) [​](https://d3js.org/d3-shape/radial-area\#areaRadial_curve)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Equivalent to [_area_.curve](https://d3js.org/d3-shape/area#area_curve). Note that [curveMonotoneX](https://d3js.org/d3-shape/curve#curveMonotoneX) or [curveMonotoneY](https://d3js.org/d3-shape/curve#curveMonotoneY) are not recommended for radial areas because they assume that the data is monotonic in _x_ or _y_, which is typically untrue of radial areas.

js

```
const area = d3.areaRadial().curve(d3.curveBasisClosed);
```

## _areaRadial_.context( _context_) [​](https://d3js.org/d3-shape/radial-area\#areaRadial_context)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Equivalent to [_area_.context](https://d3js.org/d3-shape/area#area_context).

js

```
const context = canvas.getContext("2d");
const area = d3.areaRadial().context(context);
```

## _areaRadial_.lineInnerRadius() [​](https://d3js.org/d3-shape/radial-area\#areaRadial_lineInnerRadius)

An alias for [_areaRadial_.lineStartAngle](https://d3js.org/d3-shape/radial-area#areaRadial_lineStartAngle).

## _areaRadial_.lineStartAngle() [​](https://d3js.org/d3-shape/radial-area\#areaRadial_lineStartAngle)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Returns a new [radial line generator](https://d3js.org/d3-shape/radial-line) that has this radial area generator’s current [defined accessor](https://d3js.org/d3-shape/radial-area#areaRadial_defined), [curve](https://d3js.org/d3-shape/radial-area#areaRadial_curve) and [context](https://d3js.org/d3-shape/radial-area#areaRadial_context). The line’s [angle accessor](https://d3js.org/d3-shape/radial-line#lineRadial_angle) is this area’s [start angle accessor](https://d3js.org/d3-shape/radial-area#areaRadial_startAngle), and the line’s [radius accessor](https://d3js.org/d3-shape/radial-line#lineRadial_radius) is this area’s [inner radius accessor](https://d3js.org/d3-shape/radial-area#areaRadial_innerRadius).

## _areaRadial_.lineEndAngle() [​](https://d3js.org/d3-shape/radial-area\#areaRadial_lineEndAngle)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Returns a new [radial line generator](https://d3js.org/d3-shape/radial-line#lineRadial) that has this radial area generator’s current [defined accessor](https://d3js.org/d3-shape/radial-area#areaRadial_defined), [curve](https://d3js.org/d3-shape/radial-area#areaRadial_curve) and [context](https://d3js.org/d3-shape/radial-area#areaRadial_context). The line’s [angle accessor](https://d3js.org/d3-shape/radial-line#lineRadial_angle) is this area’s [end angle accessor](https://d3js.org/d3-shape/radial-area#areaRadial_endAngle), and the line’s [radius accessor](https://d3js.org/d3-shape/radial-line#lineRadial_radius) is this area’s [inner radius accessor](https://d3js.org/d3-shape/radial-area#areaRadial_innerRadius).

## _areaRadial_.lineOuterRadius() [​](https://d3js.org/d3-shape/radial-area\#areaRadial_lineOuterRadius)

[Source](https://github.com/d3/d3-shape/blob/main/src/areaRadial.js) · Returns a new [radial line generator](https://d3js.org/d3-shape/radial-line#lineRadial) that has this radial area generator’s current [defined accessor](https://d3js.org/d3-shape/radial-area#areaRadial_defined), [curve](https://d3js.org/d3-shape/radial-area#areaRadial_curve) and [context](https://d3js.org/d3-shape/radial-area#areaRadial_context). The line’s [angle accessor](https://d3js.org/d3-shape/radial-line#lineRadial_angle) is this area’s [start angle accessor](https://d3js.org/d3-shape/radial-area#areaRadial_startAngle), and the line’s [radius accessor](https://d3js.org/d3-shape/radial-line#lineRadial_radius) is this area’s [outer radius accessor](https://d3js.org/d3-shape/radial-area#areaRadial_outerRadius).

## D3.js Link Generator
[Skip to content](https://d3js.org/d3-shape/link#VPContent)

On this page

# Links [​](https://d3js.org/d3-shape/link\#links)

[Examples](https://observablehq.com/@d3/tidy-tree) · The link shape generates a smooth cubic Bézier curve from a source point to a target point. The tangents of the curve at the start and end are either [vertical](https://d3js.org/d3-shape/link#linkVertical) or [horizontal](https://d3js.org/d3-shape/link#linkHorizontal). See also [radial links](https://d3js.org/d3-shape/radial-link).

## link( _curve_) [​](https://d3js.org/d3-shape/link\#link)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · Returns a new [link generator](https://d3js.org/d3-shape/link#_link) using the specified _curve_. For example, to visualize [links](https://d3js.org/d3-hierarchy/hierarchy#node_links) in a [tree diagram](https://d3js.org/d3-hierarchy/tree) rooted on the top edge of the display, you might say:

js

```
const link = d3.link(d3.curveBumpY)
    .x((d) => d.x)
    .y((d) => d.y);
```

## linkVertical() [​](https://d3js.org/d3-shape/link\#linkVertical)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · Shorthand for [link](https://d3js.org/d3-shape/link#link) with [curveBumpY](https://d3js.org/d3-shape/curve#curveBumpY); suitable for visualizing [links](https://d3js.org/d3-hierarchy/hierarchy#node_links) in a [tree diagram](https://d3js.org/d3-hierarchy/tree) rooted on the top edge of the display. Equivalent to:

js

```
const link = d3.link(d3.curveBumpY);
```

## linkHorizontal() [​](https://d3js.org/d3-shape/link\#linkHorizontal)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · Shorthand for [link](https://d3js.org/d3-shape/link#link) with [curveBumpX](https://d3js.org/d3-shape/curve#curveBumpX); suitable for visualizing [links](https://d3js.org/d3-hierarchy/hierarchy#node_links) in a [tree diagram](https://d3js.org/d3-hierarchy/tree) rooted on the left edge of the display. Equivalent to:

js

```
const link = d3.link(d3.curveBumpX);
```

## _link_(... _arguments_) [​](https://d3js.org/d3-shape/link\#_link)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · Generates a link for the given _arguments_. The _arguments_ are arbitrary; they are propagated to the link generator’s accessor functions along with the `this` object. With the default settings, an object with _source_ and _target_ properties is expected.

js

```
link({source: [100, 100], target: [300, 300]}) // "M100,100C200,100,200,300,300,300"
```

## _link_.source( _source_) [​](https://d3js.org/d3-shape/link\#link_source)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · If _source_ is specified, sets the source accessor to the specified function and returns this link generator.

js

```
const link = d3.linkHorizontal().source((d) => d[0]);
```

If _source_ is not specified, returns the current source accessor.

js

```
link.source() // (d) => d[0]
```

The source accessor defaults to:

js

```
function source(d) {
  return d.source;
}
```

## _link_.target( _target_) [​](https://d3js.org/d3-shape/link\#link_target)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · If _target_ is specified, sets the target accessor to the specified function and returns this link generator.

js

```
const link = d3.linkHorizontal().target((d) => d[1]);
```

If _target_ is not specified, returns the current target accessor.

js

```
link.target() // (d) => d[1]
```

The target accessor defaults to:

js

```
function target(d) {
  return d.target;
}
```

## _link_.x( _x_) [​](https://d3js.org/d3-shape/link\#link_x)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · If _x_ is specified, sets the _x_-accessor to the specified function or number and returns this link generator.

js

```
const link = d3.linkHorizontal().x((d) => x(d.x));
```

If _x_ is not specified, returns the current x accessor.

js

```
link.x() // (d) => x(d.x)
```

The x accessor defaults to:

js

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

## _link_.y( _y_) [​](https://d3js.org/d3-shape/link\#link_y)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · If _y_ is specified, sets the _y_-accessor to the specified function or number and returns this link generator.

js

```
const link = d3.linkHorizontal().y((d) => y(d.y));
```

If _y_ is not specified, returns the current y accessor.

js

```
link.y() // (d) => y(d.y)
```

The y accessor defaults to:

js

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

## _link_.context( _context_) [​](https://d3js.org/d3-shape/link\#link_context)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · If _context_ is specified, sets the context and returns this link generator.

js

```
const context = canvas.getContext("2d");
const link = d3.link().context(context);
```

If _context_ is not specified, returns the current context.

js

```
link.context() // context
```

The context defaults to null. If the context is not null, then the [generated link](https://d3js.org/d3-shape/link#_link) is rendered to this context as a sequence of [path method](http://www.w3.org/TR/2dcontext/#canvaspathmethods) calls. Otherwise, a [path data](http://www.w3.org/TR/SVG/paths.html#PathData) string representing the generated link is returned. See also [d3-path](https://d3js.org/d3-path).

## _link_.digits( _digits_) [​](https://d3js.org/d3-shape/link\#link_digits)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · If _digits_ is specified, sets the maximum number of digits after the decimal separator and returns this link generator.

js

```
const link = d3.link().digits(3);
```

If _digits_ is not specified, returns the current maximum fraction digits, which defaults to 3.

js

```
link.digits() // 3
```

This option only applies when the associated [_context_](https://d3js.org/d3-shape/link#link_context) is null, as when this link generator is used to produce [path data](http://www.w3.org/TR/SVG/paths.html#PathData).

## Data Fetching and Parsing
[Skip to content](https://d3js.org/d3-fetch#VPContent)

On this page

# d3-fetch [​](https://d3js.org/d3-fetch\#d3-fetch)

This module provides convenient parsing on top of [Fetch](https://fetch.spec.whatwg.org/). For example, to load a text file:

js

```
const text = await d3.text("hello-world.txt"); // "Hello, world!"
```

To load and parse a CSV file:

js

```
const data = await d3.csv("hello-world.csv"); // [{"Hello": "world"}, …]
```

This module has built-in support for parsing [JSON](https://d3js.org/d3-fetch#json), [CSV](https://d3js.org/d3-fetch#csv), and [TSV](https://d3js.org/d3-fetch#tsv). You can parse additional formats by using [text](https://d3js.org/d3-fetch#text) directly. (This module replaced [d3-request](https://github.com/d3/d3-request).)

## blob( _input_, _init_) [​](https://d3js.org/d3-fetch\#blob)

js

```
const blob = await d3.blob("example.db");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/blob.js) · Fetches the binary file at the specified _input_ URL as a Blob. If _init_ is specified, it is passed along to the underlying call to [fetch](https://fetch.spec.whatwg.org/#fetch-method); see [RequestInit](https://fetch.spec.whatwg.org/#requestinit) for allowed fields.

## buffer( _input_, _init_) [​](https://d3js.org/d3-fetch\#buffer)

js

```
const buffer = await d3.buffer("example.db");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/buffer.js) · Fetches the binary file at the specified _input_ URL as an ArrayBuffer. If _init_ is specified, it is passed along to the underlying call to [fetch](https://fetch.spec.whatwg.org/#fetch-method); see [RequestInit](https://fetch.spec.whatwg.org/#requestinit) for allowed fields.

## csv( _input_, _init_, _row_) [​](https://d3js.org/d3-fetch\#csv)

js

```
const data = await d3.csv("example.csv");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/dsv.js) · Equivalent to [d3.dsv](https://d3js.org/d3-fetch#dsv) with the comma character as the delimiter.

## dsv( _delimiter_, _input_, _init_, _row_) [​](https://d3js.org/d3-fetch\#dsv)

js

```
const data = await d3.dsv(",", "example.csv");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/dsv.js) · Fetches the [DSV](https://d3js.org/d3-dsv) file at the specified _input_ URL. If _init_ is specified, it is passed along to the underlying call to [fetch](https://fetch.spec.whatwg.org/#fetch-method); see [RequestInit](https://fetch.spec.whatwg.org/#requestinit) for allowed fields. An optional _row_ conversion function may be specified to map and filter row objects to a more-specific representation; see [_dsv_.parse](https://d3js.org/d3-dsv#dsv_parse) for details. For example:

js

```
const data = await d3.dsv(",", "example.csv", (d) => {
  return {
    year: new Date(+d.Year, 0, 1), // convert "Year" column to Date
    make: d.Make,
    model: d.Model,
    length: +d.Length // convert "Length" column to number
  };
});
```

If only one of _init_ and _row_ is specified, it is interpreted as the _row_ conversion function if it is a function, and otherwise an _init_ object. See also [d3.csv](https://d3js.org/d3-fetch#csv) and [d3.tsv](https://d3js.org/d3-fetch#tsv).

## html( _input_, _init_) [​](https://d3js.org/d3-fetch\#html)

js

```
const document = await d3.html("example.html");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/xml.js) · Fetches the file at the specified _input_ URL as [text](https://d3js.org/d3-fetch#text) and then [parses it](https://developer.mozilla.org/docs/Web/API/DOMParser) as HTML. If _init_ is specified, it is passed along to the underlying call to [fetch](https://fetch.spec.whatwg.org/#fetch-method); see [RequestInit](https://fetch.spec.whatwg.org/#requestinit) for allowed fields.

## image( _input_, _init_) [​](https://d3js.org/d3-fetch\#image)

js

```
const image = await d3.image("example.png");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/image.js) · Fetches the image at the specified _input_ URL. If _init_ is specified, sets any additional properties on the image before loading. For example, to enable an anonymous [cross-origin request](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image):

js

```
const image = await d3.image("https://example.com/image.png", {crossOrigin: "anonymous"});
```

## json( _input_, _init_) [​](https://d3js.org/d3-fetch\#json)

js

```
const data = await d3.json("example.json");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/json.js) · Fetches the [JSON](http://json.org/) file at the specified _input_ URL. If _init_ is specified, it is passed along to the underlying call to [fetch](https://fetch.spec.whatwg.org/#fetch-method); see [RequestInit](https://fetch.spec.whatwg.org/#requestinit) for allowed fields. If the server returns a status code of [204 No Content](https://developer.mozilla.org/docs/Web/HTTP/Status/204) or [205 Reset Content](https://developer.mozilla.org/docs/Web/HTTP/Status/205), the promise resolves to `undefined`.

## svg( _input_, _init_) [​](https://d3js.org/d3-fetch\#svg)

js

```
const document = await d3.svg("example.svg");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/xml.js) · Fetches the file at the specified _input_ URL as [text](https://d3js.org/d3-fetch#text) and then [parses it](https://developer.mozilla.org/docs/Web/API/DOMParser) as SVG. If _init_ is specified, it is passed along to the underlying call to [fetch](https://fetch.spec.whatwg.org/#fetch-method); see [RequestInit](https://fetch.spec.whatwg.org/#requestinit) for allowed fields.

## text( _input_, _init_) [​](https://d3js.org/d3-fetch\#text)

js

```
const text = await d3.text("example.txt");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/text.js) · Fetches the text file at the specified _input_ URL. If _init_ is specified, it is passed along to the underlying call to [fetch](https://fetch.spec.whatwg.org/#fetch-method); see [RequestInit](https://fetch.spec.whatwg.org/#requestinit) for allowed fields.

## tsv(input, init, row) [​](https://d3js.org/d3-fetch\#tsv)

js

```
const data = await d3.tsv("example.tsv");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/dsv.js) · Equivalent to [d3.dsv](https://d3js.org/d3-fetch#dsv) with the tab character as the delimiter.

## xml( _input_, _init_) [​](https://d3js.org/d3-fetch\#xml)

js

```
const document = await d3.xml("example.xml");
```

[Source](https://github.com/d3/d3-fetch/blob/main/src/xml.js) · Fetches the file at the specified _input_ URL as [text](https://d3js.org/d3-fetch#text) and then [parses it](https://developer.mozilla.org/docs/Web/API/DOMParser) as XML. If _init_ is specified, it is passed along to the underlying call to [fetch](https://fetch.spec.whatwg.org/#fetch-method); see [RequestInit](https://fetch.spec.whatwg.org/#requestinit) for allowed fields.

## D3 Dispatch Mechanism
[Skip to content](https://d3js.org/d3-dispatch#VPContent)

On this page

# d3-dispatch [​](https://d3js.org/d3-dispatch\#d3-dispatch)

Dispatching is a low-level interaction mechanism that allows you to register named callbacks and then call them with arbitrary arguments. A variety of D3 interaction components, such as [d3-drag](https://d3js.org/d3-drag), use [dispatch](https://d3js.org/d3-dispatch#dispatch) to emit events to listeners. Think of this as [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) except every listener has a well-defined name so it’s easy to remove or replace them.

For example, to create a dispatch for _start_ and _end_ events:

js

```
const dispatch = d3.dispatch("start", "end");
```

You can then register callbacks for these events using [_dispatch_.on](https://d3js.org/d3-dispatch#dispatch_on):

js

```
dispatch.on("start", callback1);
dispatch.on("start.foo", callback2);
dispatch.on("end", callback3);
```

Then, you can invoke all the _start_ callbacks using [_dispatch_.call](https://d3js.org/d3-dispatch#dispatch_call) or [_dispatch_.apply](https://d3js.org/d3-dispatch#dispatch_apply):

js

```
dispatch.call("start");
```

Like _function_.call, you may also specify the `this` context and any arguments:

js

```
dispatch.call("start", {about: "I am a context object"}, "I am an argument");
```

## dispatch(... _types_) [​](https://d3js.org/d3-dispatch\#dispatch)

[Source](https://github.com/d3/d3-dispatch/blob/main/src/dispatch.js) · Creates a new dispatch for the specified event _types_. Each _type_ is a string, such as `"start"` or `"end"`.

## _dispatch_.on( _typenames_, _callback_) [​](https://d3js.org/d3-dispatch\#dispatch_on)

[Source](https://github.com/d3/d3-dispatch/blob/main/src/dispatch.js) · Adds, removes or gets the _callback_ for the specified _typenames_. If a _callback_ function is specified, it is registered for the specified (fully-qualified) _typenames_. If a callback was already registered for the given _typenames_, the existing callback is removed before the new callback is added.

The specified _typenames_ is a string, such as `start` or `end.foo`. The type may be optionally followed by a period ( `.`) and a name; the optional name allows multiple callbacks to be registered to receive events of the same type, such as `start.foo` and `start.bar`. To specify multiple typenames, separate typenames with spaces, such as `start end` or `start.foo start.bar`.

To remove all callbacks for a given name `foo`, say `dispatch.on(".foo", null)`.

If _callback_ is not specified, returns the current callback for the specified _typenames_, if any. If multiple typenames are specified, the first matching callback is returned.

## _dispatch_.copy() [​](https://d3js.org/d3-dispatch\#dispatch_copy)

[Source](https://github.com/d3/d3-dispatch/blob/main/src/dispatch.js) · Returns a copy of this dispatch object. Changes to this dispatch do not affect the returned copy and _vice versa_.

## _dispatch_.call( _type_, _that_, ... _arguments_) [​](https://d3js.org/d3-dispatch\#dispatch_call)

[Source](https://github.com/d3/d3-dispatch/blob/main/src/dispatch.js) · Like [_function_.call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), invokes each registered callback for the specified _type_, passing the callback the specified _...argument_, with _that_ as the `this` context. See [_dispatch_.apply](https://d3js.org/d3-dispatch#dispatch_apply) for more information.

## _dispatch_.apply( _type_, _that_, _arguments_) [​](https://d3js.org/d3-dispatch\#dispatch_apply)

[Source](https://github.com/d3/d3-dispatch/blob/main/src/dispatch.js) · Like [_function_.apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), invokes each registered callback for the specified _type_, passing the callback the specified _arguments_, with _that_ as the `this` context. For example, if you wanted to dispatch your _custom_ callbacks after handling a native _click_ event, while preserving the current `this` context and arguments, you could say:

js

```
selection.on("click", function() {
  dispatch.apply("custom", this, arguments);
});
```

You can pass whatever arguments you want to callbacks; most commonly, you might create an object that represents an event, or pass the current datum ( _d_) and index ( _i_). See [function.call](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call) and [function.apply](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Apply) for further information.

## D3.js Ribbon Diagrams
[Skip to content](https://d3js.org/d3-chord/ribbon#VPContent)

On this page

# Ribbons [​](https://d3js.org/d3-chord/ribbon\#ribbons)

A ribbon visually represents the volume of flow between two nodes in a [chord diagram](https://d3js.org/d3-chord). Ribbons come in two varieties: [ribbon](https://d3js.org/d3-chord/ribbon#ribbon) represents a bidirectional flow, while [ribbonArrow](https://d3js.org/d3-chord/ribbon#ribbonArrow) represents a unidirectional flow. The latter is suitable for [chordDirected](https://d3js.org/d3-chord/chord#chordDirected).

## ribbon() [​](https://d3js.org/d3-chord/ribbon\#ribbon)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · Creates a new ribbon generator with the default settings.

js

```
const ribbon = d3.ribbon();
```

## _ribbon_(... _arguments_) [​](https://d3js.org/d3-chord/ribbon\#_ribbon)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · Generates a ribbon for the given _arguments_. The _arguments_ are arbitrary; they are propagated to the ribbon generator’s accessor functions along with the `this` object. For example, with the default settings, a [chord object](https://d3js.org/d3-chord/chord) is expected:

js

```
ribbon({
  source: {startAngle: 0.7524114, endAngle: 1.1212972, radius: 240},
  target: {startAngle: 1.8617078, endAngle: 1.9842927, radius: 240}
}) // "M164.0162810494058,-175.21032946354026A240,240,0,0,1,216.1595644740915,-104.28347273835429Q0,0,229.9158815306728,68.8381247563705A240,240,0,0,1,219.77316791012538,96.43523560788266Q0,0,164.0162810494058,-175.21032946354026Z"
```

If the ribbon generator has a [context](https://d3js.org/d3-chord/ribbon#ribbon_context), then the ribbon is rendered to this context as a sequence of path method calls and this function returns void. Otherwise, a path data string is returned.

## _ribbon_.source( _source_) [​](https://d3js.org/d3-chord/ribbon\#ribbon_source)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · If _source_ is specified, sets the source accessor to the specified function and returns this ribbon generator. If _source_ is not specified, returns the current source accessor, which defaults to:

js

```
function source(d) {
  return d.source;
}
```

## _ribbon_.target( _target_) [​](https://d3js.org/d3-chord/ribbon\#ribbon_target)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · If _target_ is specified, sets the target accessor to the specified function and returns this ribbon generator. If _target_ is not specified, returns the current target accessor, which defaults to:

js

```
function target(d) {
  return d.target;
}
```

## _ribbon_.radius( _radius_) [​](https://d3js.org/d3-chord/ribbon\#ribbon_radius)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · If _radius_ is specified, sets the source and target radius accessor to the specified function and returns this ribbon generator. For example to set a fixed radius of 240 pixels:

js

```
const ribbon = d3.ribbon().radius(240);
```

Now the arguments you pass to [_ribbon_](https://d3js.org/d3-chord/ribbon#_ribbon) do not need to specify a _radius_ property on the source and target.

js

```
ribbon({
  source: {startAngle: 0.7524114, endAngle: 1.1212972},
  target: {startAngle: 1.8617078, endAngle: 1.9842927}
}) // "M164.0162810494058,-175.21032946354026A240,240,0,0,1,216.1595644740915,-104.28347273835429Q0,0,229.9158815306728,68.8381247563705A240,240,0,0,1,219.77316791012538,96.43523560788266Q0,0,164.0162810494058,-175.21032946354026Z"
```

If _radius_ is not specified, returns the current source radius accessor, which defaults to:

js

```
function radius(d) {
  return d.radius;
}
```

## _ribbon_.sourceRadius( _radius_) [​](https://d3js.org/d3-chord/ribbon\#ribbon_sourceRadius)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · If _radius_ is specified, sets the source radius accessor to the specified function and returns this ribbon generator. If _radius_ is not specified, returns the current source radius accessor, which defaults to:

js

```
function radius(d) {
  return d.radius;
}
```

## _ribbon_.targetRadius( _radius_) [​](https://d3js.org/d3-chord/ribbon\#ribbon_targetRadius)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · If _radius_ is specified, sets the target radius accessor to the specified function and returns this ribbon generator. If _radius_ is not specified, returns the current target radius accessor, which defaults to:

js

```
function radius(d) {
  return d.radius;
}
```

By convention, the target radius in asymmetric chord diagrams is typically inset from the source radius, resulting in a gap between the end of the directed link and its associated group arc.

## _ribbon_.startAngle( _angle_) [​](https://d3js.org/d3-chord/ribbon\#ribbon_startAngle)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · If _angle_ is specified, sets the start angle accessor to the specified function and returns this ribbon generator. If _angle_ is not specified, returns the current start angle accessor, which defaults to:

js

```
function startAngle(d) {
  return d.startAngle;
}
```

The _angle_ is specified in radians, with 0 at - _y_ (12 o’clock) and positive angles proceeding clockwise.

## _ribbon_.endAngle( _angle_) [​](https://d3js.org/d3-chord/ribbon\#ribbon_endAngle)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · If _angle_ is specified, sets the end angle accessor to the specified function and returns this ribbon generator. If _angle_ is not specified, returns the current end angle accessor, which defaults to:

js

```
function endAngle(d) {
  return d.endAngle;
}
```

The _angle_ is specified in radians, with 0 at - _y_ (12 o’clock) and positive angles proceeding clockwise.

## _ribbon_.padAngle( _angle_) [​](https://d3js.org/d3-chord/ribbon\#ribbon_padAngle)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · If _angle_ is specified, sets the pad angle accessor to the specified function and returns this ribbon generator. If _angle_ is not specified, returns the current pad angle accessor, which defaults to:

js

```
function padAngle() {
  return 0;
}
```

The pad angle specifies the angular gap between adjacent ribbons.

## _ribbon_.context( _context_) [​](https://d3js.org/d3-chord/ribbon\#ribbon_context)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · If _context_ is specified, sets the context and returns this ribbon generator. If _context_ is not specified, returns the current context, which defaults to null. If the context is not null, then the [generated ribbon](https://d3js.org/d3-chord/ribbon#_ribbon) is rendered to this context as a sequence of [path method](http://www.w3.org/TR/2dcontext/#canvaspathmethods) calls. Otherwise, a [path data](http://www.w3.org/TR/SVG/paths.html#PathData) string representing the generated ribbon is returned. See also [d3-path](https://d3js.org/d3-path).

## ribbonArrow() [​](https://d3js.org/d3-chord/ribbon\#ribbonArrow)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · Creates a new arrow ribbon generator with the default settings. See also [chordDirected](https://d3js.org/d3-chord/chord#chordDirected).

## _ribbonArrow_.headRadius( _radius_) [​](https://d3js.org/d3-chord/ribbon\#ribbonArrow_headRadius)

[Source](https://github.com/d3/d3-chord/blob/main/src/ribbon.js) · If _radius_ is specified, sets the arrowhead radius accessor to the specified function and returns this ribbon generator. If _radius_ is not specified, returns the current arrowhead radius accessor, which defaults to:

js

```
function headRadius() {
  return 10;
}
```

## DSV Parser and Formatter
[Skip to content](https://d3js.org/d3-dsv#VPContent)

On this page

# d3-dsv [​](https://d3js.org/d3-dsv\#d3-dsv)

This module provides a parser and formatter for delimiter-separated values, most commonly [comma-separated values](https://en.wikipedia.org/wiki/Comma-separated_values) (CSV) or tab-separated values (TSV). These tabular formats are popular with spreadsheet programs such as Microsoft Excel, and are often more space-efficient than JSON. This implementation is based on [RFC 4180](http://tools.ietf.org/html/rfc4180).

For example, to parse:

js

```
d3.csvParse("foo,bar\n1,2") // [{foo: "1", bar: "2"}, columns: ["foo", "bar"]]
```

js

```
d3.tsvParse("foo\tbar\n1\t2") // [{foo: "1", bar: "2"}, columns: ["foo", "bar"]]
```

To format:

js

```
d3.csvFormat([{foo: "1", bar: "2"}]) // "foo,bar\n1,2"
```

js

```
d3.tsvFormat([{foo: "1", bar: "2"}]) // "foo\tbar\n1\t2"
```

To use a different delimiter, such as “\|” for pipe-separated values, use [d3.dsvFormat](https://d3js.org/d3-dsv#dsvFormat):

js

```
d3.dsvFormat("|").parse("foo|bar\n1|2")) // [{foo: "1", bar: "2"}, columns: ["foo", "bar"]]
```

For easy loading of DSV files in a browser, see [d3-fetch](https://d3js.org/d3-fetch)’s [d3.csv](https://d3js.org/d3-fetch#csv), [d3.tsv](https://d3js.org/d3-fetch#tsv) and [d3.dsv](https://d3js.org/d3-fetch#dsv) methods.

## dsvFormat( _delimiter_) [​](https://d3js.org/d3-dsv\#dsvFormat)

js

```
const csv = d3.dsvFormat(",");
```

[Source](https://github.com/d3/d3-dsv/blob/main/src/dsv.js) · Constructs a new DSV parser and formatter for the specified _delimiter_. The _delimiter_ must be a single character ( _i.e._, a single 16-bit code unit); so, ASCII delimiters are fine, but emoji delimiters are not.

## _dsv_.parse( _string_, _row_) [​](https://d3js.org/d3-dsv\#dsv_parse)

CAUTION

This method requires the unsafe-eval [content security policy](https://d3js.org/d3-dsv#content-security-policy).

js

```
d3.csvParse("foo,bar\n1,2") // [{foo: "1", bar: "2"}, columns: ["foo", "bar"]]
```

[Source](https://github.com/d3/d3-dsv/blob/main/src/dsv.js) · Parses the specified _string_, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows.

Unlike [_dsv_.parseRows](https://d3js.org/d3-dsv#dsv_parseRows), this method requires that the first line of the DSV content contains a delimiter-separated list of column names; these column names become the attributes on the returned objects. For example, consider the following CSV file:

```
Year,Make,Model,Length
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
```

The resulting JavaScript array is:

js

```
[\
  {"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"},\
  {"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"}\
]
```

The returned array also exposes a `columns` property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). For example:

js

```
data.columns // ["Year", "Make", "Model", "Length"]
```

If the column names are not unique, only the last value is returned for each name; to access all values, use [_dsv_.parseRows](https://d3js.org/d3-dsv#dsv_parseRows) instead (see [example](https://observablehq.com/@d3/parse-csv-with-duplicate-column-names)).

If a _row_ conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the `+` operator), but better is to specify a _row_ conversion function. See [d3.autoType](https://d3js.org/d3-dsv#autoType) for a convenient _row_ conversion function that infers and coerces common types like numbers and strings.

If a _row_ conversion function is specified, the specified function is invoked for each row, being passed an object representing the current row ( `d`), the index ( `i`) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, the row is skipped and will be omitted from the array returned by _dsv_.parse; otherwise, the returned value defines the corresponding row object. For example:

js

```
const data = d3.csvParse(string, (d) => {
  return {
    year: new Date(+d.Year, 0, 1), // lowercase and convert "Year" to Date
    make: d.Make, // lowercase
    model: d.Model, // lowercase
    length: +d.Length // lowercase and convert "Length" to number
  };
});
```

Note: using `+` or `Number` rather than [parseInt](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt) or [parseFloat](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat) is typically faster, though more restrictive. For example, `"30px"` when coerced using `+` returns `NaN`, while parseInt and parseFloat return `30`.

## _dsv_.parseRows( _string_, _row_) [​](https://d3js.org/d3-dsv\#dsv_parseRows)

js

```
d3.csvParseRows("foo,bar\n1,2") // [["foo", "bar"], ["1", "2"]]
```

[Source](https://github.com/d3/d3-dsv/blob/main/src/dsv.js) · Parses the specified _string_, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of arrays representing the parsed rows.

Unlike [_dsv_.parse](https://d3js.org/d3-dsv#dsv_parse), this method treats the header line as a standard row, and should be used whenever DSV content does not contain a header. Each row is represented as an array rather than an object. Rows may have variable length. For example, consider the following CSV file, which notably lacks a header line:

```
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
```

The resulting JavaScript array is:

js

```
[\
  ["1997", "Ford", "E350", "2.34"],\
  ["2000", "Mercury", "Cougar", "2.38"]\
]
```

If a _row_ conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the `+` operator), but better is to specify a _row_ conversion function. See [d3.autoType](https://d3js.org/d3-dsv#autoType) for a convenient _row_ conversion function that infers and coerces common types like numbers and strings.

If a _row_ conversion function is specified, the specified function is invoked for each row, being passed an array representing the current row ( `d`), the index ( `i`) starting at zero for the first row, and the array of column names. If the returned value is null or undefined, the row is skipped and will be omitted from the array returned by _dsv_.parse; otherwise, the returned value defines the corresponding row object. For example:

js

```
const data = d3.csvParseRows(string, (d, i) => {
  return {
    year: new Date(+d[0], 0, 1), // convert first column to Date
    make: d[1],
    model: d[2],
    length: +d[3] // convert fourth column to number
  };
});
```

In effect, _row_ is similar to applying a [map](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map) and [filter](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter) operator to the returned rows.

## _dsv_.format( _rows_, _columns_) [​](https://d3js.org/d3-dsv\#dsv_format)

js

```
d3.csvFormat([{foo: "1", bar: "2"}]) // "foo,bar\n1,2"
```

js

```
d3.csvFormat([{foo: "1", bar: "2"}], ["foo"]) // "foo\n1"
```

[Source](https://github.com/d3/d3-dsv/blob/main/src/dsv.js) · Formats the specified array of object _rows_ as delimiter-separated values, returning a string. This operation is the inverse of [_dsv_.parse](https://d3js.org/d3-dsv#dsv_parse). Each row will be separated by a newline ( `\n`), and each column within each row will be separated by the delimiter (such as a comma, `,`). Values that contain either the delimiter, a double-quote ( `"`) or a newline will be escaped using double-quotes.

If _columns_ is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in _rows_; the order of columns is nondeterministic. If _columns_ is specified, it is an array of strings representing the column names. For example:

js

```
const string = d3.csvFormat(data, ["year", "make", "model", "length"]);
```

All fields on each row object will be coerced to strings. If the field value is null or undefined, the empty string is used. If the field value is a Date, the [ECMAScript date-time string format](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-date-time-string-format) (a subset of ISO 8601) is used: for example, dates at UTC midnight are formatted as `YYYY-MM-DD`. For more control over which and how fields are formatted, first map _rows_ to an array of array of string, and then use [_dsv_.formatRows](https://d3js.org/d3-dsv#dsv_formatRows).

## _dsv_.formatBody( _rows_, _columns_) [​](https://d3js.org/d3-dsv\#dsv_formatBody)

js

```
d3.csvFormatBody([{foo: "1", bar: "2"}]) // "1,2"
```

js

```
d3.csvFormatBody([{foo: "1", bar: "2"}], ["foo"]) // "1"
```

[Source](https://github.com/d3/d3-dsv/blob/main/src/dsv.js) · Equivalent to [_dsv_.format](https://d3js.org/d3-dsv#dsv_format), but omits the header row. This is useful, for example, when appending rows to an existing file.

## _dsv_.formatRows( _rows_) [​](https://d3js.org/d3-dsv\#dsv_formatRows)

js

```
d3.csvFormatRows([["foo", "bar"], ["1", "2"]]) // "foo,bar\n1,2"
```

[Source](https://github.com/d3/d3-dsv/blob/main/src/dsv.js) · Formats the specified array of array of string _rows_ as delimiter-separated values, returning a string. This operation is the reverse of [_dsv_.parseRows](https://d3js.org/d3-dsv#dsv_parseRows). Each row will be separated by a newline ( `\n`), and each column within each row will be separated by the delimiter (such as a comma, `,`). Values that contain either the delimiter, a double-quote (") or a newline will be escaped using double-quotes.

To convert an array of objects to an array of arrays while explicitly specifying the columns, use [_array_.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). For example:

js

```
const string = d3.csvFormatRows(data.map((d, i) => {
  return [\
    d.year.getUTCFullYear(), // Assuming d.year is a Date object.\
    d.make,\
    d.model,\
    d.length\
  ];
}));
```

If you like, you can also [_array_.concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) this result with an array of column names to generate the first row:

js

```
const string = d3.csvFormatRows([[\
    "year",\
    "make",\
    "model",\
    "length"\
  ]].concat(data.map((d, i) => {
  return [\
    d.year.getUTCFullYear(), // Assuming d.year is a Date object.\
    d.make,\
    d.model,\
    d.length\
  ];
})));
```

## _dsv_.formatRow( _row_) [​](https://d3js.org/d3-dsv\#dsv_formatRow)

js

```
d3.csvFormatRow(["foo", "bar"]) // "foo,bar"
```

[Source](https://github.com/d3/d3-dsv/blob/main/src/dsv.js) · Formats a single array _row_ of strings as delimiter-separated values, returning a string. Each column within the row will be separated by the delimiter (such as a comma, `,`). Values that contain either the delimiter, a double-quote (") or a newline will be escaped using double-quotes.

## _dsv_.formatValue( _value_) [​](https://d3js.org/d3-dsv\#dsv_formatValue)

js

```
d3.csvFormatValue("foo") // "foo"
```

[Source](https://github.com/d3/d3-dsv/blob/main/src/dsv.js) · Format a single _value_ or string as a delimiter-separated value, returning a string. A value that contains either the delimiter, a double-quote (") or a newline will be escaped using double-quotes.

## csvParse( _string_, _row_) [​](https://d3js.org/d3-dsv\#csvParse)

Equivalent to [`d3.dsvFormat(",").parse`](https://d3js.org/d3-dsv#dsv_parse).

## csvParseRows( _string_, _row_) [​](https://d3js.org/d3-dsv\#csvParseRows)

Equivalent to [`d3.dsvFormat(",").parseRows`](https://d3js.org/d3-dsv#dsv_parseRows).

## csvFormat( _rows_, _columns_) [​](https://d3js.org/d3-dsv\#csvFormat)

Equivalent to [`d3.dsvFormat(",").format`](https://d3js.org/d3-dsv#dsv_format).

## csvFormatBody( _rows_, _columns_) [​](https://d3js.org/d3-dsv\#csvFormatBody)

Equivalent to [`d3.dsvFormat(",").formatBody`](https://d3js.org/d3-dsv#dsv_formatBody).

## csvFormatRows( _rows_) [​](https://d3js.org/d3-dsv\#csvFormatRows)

Equivalent to [`d3.dsvFormat(",").formatRows`](https://d3js.org/d3-dsv#dsv_formatRows).

## csvFormatRow( _row_) [​](https://d3js.org/d3-dsv\#csvFormatRow)

Equivalent to [`d3.dsvFormat(",").formatRow`](https://d3js.org/d3-dsv#dsv_formatRow).

## csvFormatValue( _value_) [​](https://d3js.org/d3-dsv\#csvFormatValue)

Equivalent to [`d3.dsvFormat(",").formatValue`](https://d3js.org/d3-dsv#dsv_formatValue).

## tsvParse( _string_, _row_) [​](https://d3js.org/d3-dsv\#tsvParse)

Equivalent to [`d3.dsvFormat("\t").parse`](https://d3js.org/d3-dsv#dsv_parse).

## tsvParseRows( _string_, _row_) [​](https://d3js.org/d3-dsv\#tsvParseRows)

Equivalent to [`d3.dsvFormat("\t").parseRows`](https://d3js.org/d3-dsv#dsv_parseRows).

## tsvFormat( _rows_, _columns_) [​](https://d3js.org/d3-dsv\#tsvFormat)

Equivalent to [`d3.dsvFormat("\t").format`](https://d3js.org/d3-dsv#dsv_format).

## tsvFormatBody( _rows_, _columns_) [​](https://d3js.org/d3-dsv\#tsvFormatBody)

Equivalent to [`d3.dsvFormat("\t").formatBody`](https://d3js.org/d3-dsv#dsv_formatBody).

## tsvFormatRows( _rows_) [​](https://d3js.org/d3-dsv\#tsvFormatRows)

Equivalent to [`d3.dsvFormat("\t").formatRows`](https://d3js.org/d3-dsv#dsv_formatRows).

## tsvFormatRow( _row_) [​](https://d3js.org/d3-dsv\#tsvFormatRow)

Equivalent to [`d3.dsvFormat("\t").formatRow`](https://d3js.org/d3-dsv#dsv_formatRow).

## tsvFormatValue( _value_) [​](https://d3js.org/d3-dsv\#tsvFormatValue)

Equivalent to [`d3.dsvFormat("\t").formatValue`](https://d3js.org/d3-dsv#dsv_formatValue).

## autoType( _object_) [​](https://d3js.org/d3-dsv\#autoType)

[Source](https://github.com/d3/d3-dsv/blob/main/src/autoType.js) · Given an _object_ (or array) representing a parsed row, infers the types of values on the _object_ and coerces them accordingly, returning the mutated _object_. This function is intended to be used as a _row_ accessor function in conjunction with [_dsv_.parse](https://d3js.org/d3-dsv#dsv_parse) and [_dsv_.parseRows](https://d3js.org/d3-dsv#dsv_parseRows). For example, consider the following CSV file:

```
Year,Make,Model,Length
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
```

When used with [d3.csvParse](https://d3js.org/d3-dsv#csvParse),

js

```
d3.csvParse(string, d3.autoType)
```

the resulting JavaScript array is:

js

```
[\
  {"Year": 1997, "Make": "Ford", "Model": "E350", "Length": 2.34},\
  {"Year": 2000, "Make": "Mercury", "Model": "Cougar", "Length": 2.38}\
]
```

Type inference works as follows. For each _value_ in the given _object_, the [trimmed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) value is computed; the value is then re-assigned as follows:

1. If empty, then `null`.
2. If exactly `"true"`, then `true`.
3. If exactly `"false"`, then `false`.
4. If exactly `"NaN"`, then `NaN`.
5. Otherwise, if [coercible to a number](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-tonumber-applied-to-the-string-type), then a number.
6. Otherwise, if a [date-only or date-time string](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-date-time-string-format), then a Date.
7. Otherwise, a string (the original untrimmed value).

Values with leading zeroes may be coerced to numbers; for example `"08904"` coerces to `8904`. However, extra characters such as commas or units ( _e.g._, `"$1.00"`, `"(123)"`, `"1,234"` or `"32px"`) will prevent number coercion, resulting in a string.

Date strings must be in ECMAScript’s subset of the [ISO 8601 format](https://en.wikipedia.org/wiki/ISO_8601). When a date-only string such as YYYY-MM-DD is specified, the inferred time is midnight UTC; however, if a date-time string such as YYYY-MM-DDTHH:MM is specified without a time zone, it is assumed to be local time.

Automatic type inference is primarily intended to provide safe, predictable behavior in conjunction with [_dsv_.format](https://d3js.org/d3-dsv#dsv_format) and [_dsv_.formatRows](https://d3js.org/d3-dsv#dsv_formatRows) for common JavaScript types. If you need different behavior, you should implement your own row accessor function.

For more, see [the d3.autoType notebook](https://observablehq.com/@d3/d3-autotype).

## Content security policy [​](https://d3js.org/d3-dsv\#content-security-policy)

If a [content security policy](http://www.w3.org/TR/CSP/) is in place, note that [_dsv_.parse](https://d3js.org/d3-dsv#dsv_parse) requires `unsafe-eval` in the `script-src` directive, due to the (safe) use of dynamic code generation for fast parsing. (See [source](https://github.com/d3/d3-dsv/blob/main/src/dsv.js).) Alternatively, use [_dsv_.parseRows](https://d3js.org/d3-dsv#dsv_parseRows).

## Byte-order marks [​](https://d3js.org/d3-dsv\#byte-order-marks)

DSV files sometimes begin with a [byte order mark (BOM)](https://en.wikipedia.org/wiki/Byte_order_mark); saving a spreadsheet in CSV UTF-8 format from Microsoft Excel, for example, will include a BOM. On the web this is not usually a problem because the [UTF-8 decode algorithm](https://encoding.spec.whatwg.org/#utf-8-decode) specified in the Encoding standard removes the BOM. Node.js, on the other hand, [does not remove the BOM](https://github.com/nodejs/node-v0.x-archive/issues/1918) when decoding UTF-8.

If the BOM is not removed, the first character of the text is a zero-width non-breaking space. So if a CSV file with a BOM is parsed by [d3.csvParse](https://d3js.org/d3-dsv#csvParse), the first column’s name will begin with a zero-width non-breaking space. This can be hard to spot since this character is usually invisible when printed.

To remove the BOM before parsing, consider using [strip-bom](https://www.npmjs.com/package/strip-bom).

## D3.js Data Grouping
[Skip to content](https://d3js.org/d3-array/group#VPContent)

On this page

# Grouping data [​](https://d3js.org/d3-array/group\#grouping-data)

Group discrete values.

## group( _iterable_, ... _keys_) [​](https://d3js.org/d3-array/group\#group)

[Examples](https://observablehq.com/@d3/d3-group-d3-rollup) · [Source](https://github.com/d3/d3-array/blob/main/src/group.js) · Groups the specified _iterable_ of values into an [InternMap](https://d3js.org/d3-array/intern#InternMap) from _key_ to array of value. For example, to group the [_penguins_ sample dataset](https://observablehq.com/@observablehq/sample-datasets#penguins) by _species_ field:

js

```
const species = d3.group(penguins, (d) => d.species);
```

To get the elements whose _species_ field is _Adelie_:

js

```
species.get("Adelie") // Array(152)
```

If more than one _key_ is specified, a nested InternMap is returned. For example:

js

```
const speciesSex = d3.group(penguins, (d) => d.species, (d) => d.sex)
```

To get the penguins whose species is _Adelie_ and whose sex is _FEMALE_:

js

```
speciesSex.get("Adelie").get("FEMALE") // Array(73)
```

Elements are returned in the order of the first instance of each _key_.

## groups( _iterable_, ... _keys_) [​](https://d3js.org/d3-array/group\#groups)

js

```
const species = d3.groups(penguins, (d) => d.species); // [["Adelie", Array(152)], …]
```

Equivalent to [group](https://d3js.org/d3-array/group#group), but returns an array of \[ _key_, _value_\] entries instead of a map. If more than one _key_ is specified, each _value_ will be a nested array of \[ _key_, _value_\] entries. Elements are returned in the order of the first instance of each _key_.

## rollup( _iterable_, _reduce_, ... _keys_) [​](https://d3js.org/d3-array/group\#rollup)

[Examples](https://observablehq.com/@d3/d3-group-d3-rollup) · [Source](https://github.com/d3/d3-array/blob/main/src/group.js) · Groups and reduces the specified _iterable_ of values into an [InternMap](https://d3js.org/d3-array/intern#InternMap) from _key_ to reduced value. For example, to group and count the [_penguins_ sample dataset](https://observablehq.com/@observablehq/sample-datasets#penguins) by _species_ field:

js

```
const speciesCount = d3.rollup(penguins, (D) => D.length, (d) => d.species);
```

To get the count of penguins whose species is _Adelie_:

js

```
speciesCount.get("Adelie") // 152
```

If more than one _key_ is specified, a nested InternMap is returned. For example:

js

```
const speciesSexCount = d3.rollup(penguins, (D) => D.length, (d) => d.species, (d) => d.sex);
```

To get the count of penguins whose species is _Adelie_ and whose sex is _FEMALE_:

js

```
speciesSexCount.get("Adelie").get("FEMALE") // 73
```

Elements are returned in the order of the first instance of each _key_.

## rollups( _iterable_, _reduce_, ... _keys_) [​](https://d3js.org/d3-array/group\#rollups)

js

```
const speciesCounts = d3.rollups(penguins, (D) => D.length, (d) => d.species); // [["Adelie", 152], …]
```

Equivalent to [rollup](https://d3js.org/d3-array/group#rollup), but returns an array of \[ _key_, _value_\] entries instead of a map. If more than one _key_ is specified, each _value_ will be a nested array of \[ _key_, _value_\] entries. Elements are returned in the order of the first instance of each _key_.

## index( _iterable_, ... _keys_) [​](https://d3js.org/d3-array/group\#index)

Uses [rollup](https://d3js.org/d3-array/group#rollup) with a reducer that extracts the first element from each group, and throws an error if the group has more than one element. For example, to index the [_aapl_ same dataset](https://observablehq.com/@observablehq/sample-datasets#aapl) by date:

js

```
const aaplDate = d3.index(aapl, (d) => d.Date);
```

You can then quickly retrieve a value by date:

js

```
aaplDate.get(new Date("2013-12-31")).Close // 80.145714
```

Elements are returned in input order.

## indexes( _iterable_, ... _keys_) [​](https://d3js.org/d3-array/group\#indexes)

Like [index](https://d3js.org/d3-array/group#index), but returns an array of \[ _key_, _value_\] entries instead of a map. This probably isn’t useful for anything, but is included for symmetry with [groups](https://d3js.org/d3-array/group#groups) and [rollups](https://d3js.org/d3-array/group#rollups).

## flatGroup( _iterable_, ... _keys_) [​](https://d3js.org/d3-array/group\#flatGroup)

[Examples](https://observablehq.com/@d3/d3-flatgroup) · [Source](https://github.com/d3/d3-array/blob/main/src/group.js) · Equivalent to [group](https://d3js.org/d3-array/group#group), but returns a flat array of \[ _key0_, _key1_, …, _values_\] instead of nested maps; useful for iterating over all groups.

## flatRollup( _iterable_, _reduce_, ... _keys_) [​](https://d3js.org/d3-array/group\#flatRollup)

[Examples](https://observablehq.com/@d3/d3-flatgroup) · [Source](https://github.com/d3/d3-array/blob/main/src/group.js) · Equivalent to [rollup](https://d3js.org/d3-array/group#rollup), but returns a flat array of \[ _key0_, _key1_, …, _value_\] instead of nested maps; useful for iterating over all groups.

## groupSort( _iterable_, _comparator_, _key_) [​](https://d3js.org/d3-array/group\#groupSort)

[Examples](https://observablehq.com/@d3/d3-groupsort) · [Source](https://github.com/d3/d3-array/blob/main/src/groupSort.js) · Groups the specified _iterable_ of elements according to the specified _key_ function, sorts the groups according to the specified _comparator_, and then returns an array of keys in sorted order. For example, to order the species of the [_penguins_ sample dataset](https://observablehq.com/@observablehq/sample-datasets#penguins) by ascending median body mass:

js

```
d3.groupSort(penguins, (D) => d3.median(D, (d) => d.body_mass_g), (d) => d.species) // ["Adelie", "Chinstrap", "Gentoo"]
```

For descending order, negate the group value:

js

```
d3.groupSort(penguins, (D) => -d3.median(D, (d) => d.body_mass_g), (d) => d.species) // ["Gentoo", "Adelie", "Chinstrap"]
```

If a _comparator_ is passed instead of an _accessor_ ( _i.e._, if the second argument is a function that takes exactly two arguments), it will be asked to compare two groups _a_ and _b_ and should return a negative value if _a_ should be before _b_, a positive value if _a_ should be after _b_, or zero for a partial ordering.

## Center Force
[Skip to content](https://d3js.org/d3-force/center#VPContent)

On this page

# Center force [​](https://d3js.org/d3-force/center\#center-force)

The center force translates nodes uniformly so that the mean position of all nodes (the center of mass if all nodes have equal weight) is at the given position ⟨ [_x_](https://d3js.org/d3-force/center#center_x), [_y_](https://d3js.org/d3-force/center#center_y)⟩. This force modifies the positions of nodes on each application; it does not modify velocities, as doing so would typically cause the nodes to overshoot and oscillate around the desired center. This force helps keep nodes in the center of the viewport, and unlike the [position forces](https://d3js.org/d3-force/position), it does not distort their relative positions.

## forceCenter( _x_, _y_) [​](https://d3js.org/d3-force/center\#forceCenter)

[Source](https://github.com/d3/d3-force/blob/main/src/center.js) · Creates a new center force with the specified [_x_-](https://d3js.org/d3-force/center#center_x) and [_y_-](https://d3js.org/d3-force/center#center_y) coordinates. If _x_ and _y_ are not specified, they default to ⟨0,0⟩.

js

```
const center = d3.forceCenter(width / 2, height / 2);
```

## _center_.x( _x_) [​](https://d3js.org/d3-force/center\#center_x)

[Source](https://github.com/d3/d3-force/blob/main/src/center.js) · If _x_ is specified, sets the _x_-coordinate of the centering position to the specified number and returns this force. If _x_ is not specified, returns the current _x_-coordinate, which defaults to zero.

## _center_.y( _y_) [​](https://d3js.org/d3-force/center\#center_y)

[Source](https://github.com/d3/d3-force/blob/main/src/center.js) · If _y_ is specified, sets the y coordinate of the centering position to the specified number and returns this force. If _y_ is not specified, returns the current y coordinate, which defaults to zero.

## _center_.strength( _strength_) [​](https://d3js.org/d3-force/center\#center_strength)

[Examples](https://observablehq.com/@d3/forcecenter-strength) · [Source](https://github.com/d3/d3-force/blob/main/src/center.js) · If _strength_ is specified, sets the center force’s strength. A reduced strength of e.g. 0.05 softens the movements on interactive graphs in which new nodes enter or exit the graph. If _strength_ is not specified, returns the force’s current strength, which defaults to 1.

## D3 Brush Module
[Skip to content](https://d3js.org/d3-brush#VPContent)

On this page

# d3-brush [​](https://d3js.org/d3-brush\#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](https://square.github.io/crossfilter/) or live histograms:

[![Mona Lisa Histogram](https://raw.githubusercontent.com/d3/d3-brush/master/img/mona-lisa.jpg)](https://observablehq.com/@d3/mona-lisa-histogram)

The d3-brush module implements brushing for mouse and touch events using [SVG](https://www.w3.org/TR/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](https://d3js.org/d3-brush#brush-events), and then initiate a transition with [_brush_.move](https://d3js.org/d3-brush#brush_move) to snap the brush selection to semantic boundaries:

[![Brush Snapping](https://raw.githubusercontent.com/d3/d3-brush/master/img/snapping.png)](https://observablehq.com/@d3/brush-snapping-transitions)

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

[![Click-to-Recenter](https://raw.githubusercontent.com/d3/d3-brush/master/img/recenter.jpg)](https://observablehq.com/@d3/click-to-recenter-brush)

## brush() [​](https://d3js.org/d3-brush\#brush)

[Examples](https://observablehq.com/@d3/brushable-scatterplot) · [Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · Creates a new two-dimensional brush.

## brushX() [​](https://d3js.org/d3-brush\#brushX)

[Examples](https://observablehq.com/@d3/focus-context) · [Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · Creates a new one-dimensional brush along the _x_-dimension.

## brushY() [​](https://d3js.org/d3-brush\#brushY)

[Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · Creates a new one-dimensional brush along the _y_-dimension.

## _brush_( _group_) [​](https://d3js.org/d3-brush\#_brush)

[Examples](https://observablehq.com/@d3/brushable-scatterplot-matrix) · [Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · Applies the brush to the specified _group_, which must be a [selection](https://d3js.org/d3-selection) of SVG [G elements](https://www.w3.org/TR/SVG/struct.html#Groups). This function is typically not invoked directly, and is instead invoked via [_selection_.call](https://d3js.org/d3-selection/control-flow#selection_call). For example, to render a brush:

js

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

Internally, the brush uses [_selection_.on](https://d3js.org/d3-selection/events#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:

js

```
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:

html

```
<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](https://d3js.org/d3-brush#brush_extent). The selection rect covers the area defined by the current [brush selection](https://d3js.org/d3-brush#brushSelection). 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](https://d3js.org/d3-brush#brush_move).

## _brush_.move( _group_, _selection_, _event_) [​](https://d3js.org/d3-brush\#brush_move)

[Examples](https://observablehq.com/d/93b91f86f9ebc9b9) · [Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · Sets the active _selection_ of the brush on the specified _group_, which must be a [selection](https://d3js.org/d3-selection) or a [transition](https://d3js.org/d3-transition) of SVG [G elements](https://www.w3.org/TR/SVG/struct.html#Groups). The _selection_ must be defined as an array of numbers, or null to clear the brush selection. For a [two-dimensional brush](https://d3js.org/d3-brush#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](https://d3js.org/d3-brush#brushX), it must be defined as \[ _x0_, _x1_\]; for a [_y_-brush](https://d3js.org/d3-brush#brushY), 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_) [​](https://d3js.org/d3-brush\#brush_clear)

[Examples](https://observablehq.com/@d3/double-click-brush-clear) · [Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · An alias for [_brush_.move](https://d3js.org/d3-brush#brush_move) with the null selection.

## _brush_.extent( _extent_) [​](https://d3js.org/d3-brush\#brush_extent)

[Examples](https://observablehq.com/@d3/brush-snapping) · [Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · 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:

js

```
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](https://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute), or [width](https://www.w3.org/TR/SVG/struct.html#SVGElementWidthAttribute) and [height](https://www.w3.org/TR/SVG/struct.html#SVGElementHeightAttribute) attributes. Alternatively, consider using [_element_.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). (In Firefox, [_element_.clientWidth](https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth) and [_element_.clientHeight](https://developer.mozilla.org/en-US/docs/Web/API/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_) [​](https://d3js.org/d3-brush\#brush_filter)

[Examples](https://observablehq.com/@d3/brush-filter) · [Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · 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:

js

```
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_) [​](https://d3js.org/d3-brush\#brush_touchable)

[Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · 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:

js

```
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](https://d3js.org/d3-brush#_brush). 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_) [​](https://d3js.org/d3-brush\#brush_keyModifiers)

[Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · 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_) [​](https://d3js.org/d3-brush\#brush_handleSize)

[Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · 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](https://d3js.org/d3-brush#_brush) to a selection; changing the handle size does not affect brushes that were previously rendered.

## _brush_.on( _typenames_, _listener_) [​](https://d3js.org/d3-brush\#brush_on)

[Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · 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](https://d3js.org/d3-selection/events#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](https://d3js.org/d3-dispatch#dispatch_on) and [brush events](https://d3js.org/d3-brush#brush-events) for more.

## brushSelection( _node_) [​](https://d3js.org/d3-brush\#brushSelection)

[Examples](https://observablehq.com/@d3/double-click-brush-clear) · [Source](https://github.com/d3/d3-brush/blob/main/src/brush.js) · 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](https://d3js.org/d3-brush#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](https://d3js.org/d3-brush#brushX), it is \[ _x0_, _x1_\]; for a [_y_-brush](https://d3js.org/d3-brush#brushY), it is \[ _y0_, _y1_\].

## Brush events [​](https://d3js.org/d3-brush\#brush-events)

When a [brush event listener](https://d3js.org/d3-brush#brush_on) is invoked, it receives the current brush event. The _event_ object exposes several fields:

- `target` \- the associated [brush behavior](https://d3js.org/d3-brush#brush).
- `type` \- the string “start”, “brush” or “end”; see [_brush_.on](https://d3js.org/d3-brush#brush_on).
- `selection` \- the current [brush selection](https://d3js.org/d3-brush#brushSelection).
- `sourceEvent` \- the underlying input event, such as mousemove or touchmove.
- `mode` \- the string “drag”, “space”, “handle” or “center”; the mode of the brush.

## D3.js Polygon Module
[Skip to content](https://d3js.org/d3-polygon#VPContent)

On this page

# d3-polygon [​](https://d3js.org/d3-polygon\#d3-polygon)

This module provides a few basic geometric operations for two-dimensional polygons. Each polygon is represented as an array of two-element arrays \[​\[ _x0_, _y0_\], \[ _x1_, _y1_\], …\], and may either be closed (wherein the first and last point are the same) or open (wherein they are not). Typically polygons are in counterclockwise order, assuming a coordinate system where the origin is in the top-left corner.

## polygonArea( _polygon_) [​](https://d3js.org/d3-polygon\#polygonArea)

js

```
d3.polygonArea([[1, 1], [1.5, 0], [2, 1]]) // -0.5
```

[Source](https://github.com/d3/d3-polygon/blob/main/src/area.js) · Returns the signed area of the specified _polygon_. If the vertices of the polygon are in counterclockwise order (assuming a coordinate system where the origin is in the top-left corner), the returned area is positive; otherwise it is negative, or zero.

## polygonCentroid( _polygon_) [​](https://d3js.org/d3-polygon\#polygonCentroid)

js

```
d3.polygonCentroid([[1, 1], [1.5, 0], [2, 1]]) // [1.5, 0.6666666666666666]
```

[Source](https://github.com/d3/d3-polygon/blob/main/src/centroid.js) · Returns the [centroid](https://en.wikipedia.org/wiki/Centroid) of the specified _polygon_.

## polygonHull( _points_) [​](https://d3js.org/d3-polygon\#polygonHull)

js

```
d3.polygonHull(points) // [[3.0872864263338777, -1.300100095019402], [1.6559368816733773, -2.5092525689499605], …]
```

[Source](https://github.com/d3/d3-polygon/blob/main/src/hull.js) · Returns the [convex hull](https://en.wikipedia.org/wiki/Convex_hull) of the specified _points_ using [Andrew’s monotone chain algorithm](http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain). The returned hull is represented as an array containing a subset of the input _points_ arranged in counterclockwise order. Returns null if _points_ has fewer than three elements.

## polygonContains( _polygon_, _point_) [​](https://d3js.org/d3-polygon\#polygonContains)

js

```
d3.polygonContains([[1, 1], [1.5, 0], [2, 1]], [1.5, 0.667]) // true
```

[Source](https://github.com/d3/d3-polygon/blob/main/src/contains.js) · Returns true if and only if the specified _point_ is inside the specified _polygon_.

## polygonLength( _polygon_) [​](https://d3js.org/d3-polygon\#polygonLength)

js

```
d3.polygonLength([[1, 1], [1.5, 0], [2, 1]]) // 3.23606797749979
```

[Source](https://github.com/d3/d3-polygon/blob/main/src/length.js) · Returns the length of the perimeter of the specified _polygon_.

## Density Estimation
[Skip to content](https://d3js.org/d3-contour/density#VPContent)

On this page

# Density estimation [​](https://d3js.org/d3-contour/density\#density-estimation)

Contours can show the estimated density of point clouds, which is useful to avoid overplotting in large datasets. The [contourDensity](https://d3js.org/d3-contour/density#contourDensity) method implements fast two-dimensional kernel density estimation.

Here is a scatterplot showing the relationship between the idle duration and eruption duration for Old Faithful:

[![Density Contours](https://raw.githubusercontent.com/d3/d3-contour/main/img/faithful.png)](https://observablehq.com/@d3/density-contours)

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

[![Density Contours](https://raw.githubusercontent.com/d3/d3-contour/main/img/diamonds.png)](https://observablehq.com/@d3/density-contours)

## contourDensity() [​](https://d3js.org/d3-contour/density\#contourDensity)

[Examples](https://observablehq.com/@d3/density-contours) · [Source](https://github.com/d3/d3-contour/blob/main/src/density.js) · Constructs a new density estimator with the default settings.

## _density_( _data_) [​](https://d3js.org/d3-contour/density\#_density)

[Source](https://github.com/d3/d3-contour/blob/main/src/density.js) · Estimates the density contours for the given array of _data_, returning an array of [GeoJSON](http://geojson.org/geojson-spec.html) [MultiPolygon](http://geojson.org/geojson-spec.html#multipolygon) [geometry objects](http://geojson.org/geojson-spec.html#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](https://d3js.org/d3-contour/density#density_thresholds); the threshold value for each geometry object is exposed as _geometry_.value. The returned geometry objects are typically passed to [geoPath](https://d3js.org/d3-geo/path) to display, using null or [geoIdentity](https://d3js.org/d3-geo/projection#geoIdentity) as the associated projection. See also [contours](https://d3js.org/d3-contour/contour).

The x and y coordinate for each data point are computed using [_density_.x](https://d3js.org/d3-contour/density#density_x) and [_density_.y](https://d3js.org/d3-contour/density#density_y). In addition, [_density_.weight](https://d3js.org/d3-contour/density#density_weight) indicates the relative contribution of each data point (default 1). The generated contours are only accurate within the estimator’s [defined size](https://d3js.org/d3-contour/density#density_size).

## _density_.x( _x_) [​](https://d3js.org/d3-contour/density\#density_x)

[Source](https://github.com/d3/d3-contour/blob/main/src/density.js) · If _x_ is specified, sets the _x_-coordinate accessor. If _x_ is not specified, returns the current _x_-coordinate accessor, which defaults to:

js

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

## _density_.y( _y_) [​](https://d3js.org/d3-contour/density\#density_y)

[Source](https://github.com/d3/d3-contour/blob/main/src/density.js) · If _y_ is specified, sets the _y_-coordinate accessor. If _y_ is not specified, returns the current _y_-coordinate accessor, which defaults to:

js

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

## _density_.weight( _weight_) [​](https://d3js.org/d3-contour/density\#density_weight)

[Source](https://github.com/d3/d3-contour/blob/main/src/density.js) · If _weight_ is specified, sets the accessor for point weights. If _weight_ is not specified, returns the current point weight accessor, which defaults to:

js

```
function weight() {
  return 1;
}
```

## _density_.size( _size_) [​](https://d3js.org/d3-contour/density\#density_size)

[Source](https://github.com/d3/d3-contour/blob/main/src/density.js) · 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](https://d3js.org/d3-contour/density#_density) are only accurate within the defined size.

## _density_.cellSize( _cellSize_) [​](https://d3js.org/d3-contour/density\#density_cellSize)

[Source](https://github.com/d3/d3-contour/blob/main/src/density.js) · 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_) [​](https://d3js.org/d3-contour/density\#density_thresholds)

[Source](https://github.com/d3/d3-contour/blob/main/src/density.js) · 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](https://d3js.org/d3-contour/density#_density) 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 [ticks](https://d3js.org/d3-array/ticks#ticks).

## _density_.bandwidth( _bandwidth_) [​](https://d3js.org/d3-contour/density\#density_bandwidth)

[Source](https://github.com/d3/d3-contour/blob/main/src/density.js) · 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_) [​](https://d3js.org/d3-contour/density\#density_contours)

[Examples](https://observablehq.com/@d3/density-contours-data) · [Source](https://github.com/d3/d3-contour/blob/main/src/density.js) · 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.

## D3.js Band Scales
[Skip to content](https://d3js.org/d3-scale/band#VPContent)

On this page

# Band scales [​](https://d3js.org/d3-scale/band\#band-scales)

Band scales are like [ordinal scales](https://d3js.org/d3-scale/ordinal) except the output range is continuous and numeric. The scale divides the continuous range into uniform bands. Band scales are typically used for bar charts with an ordinal or categorical dimension.

## scaleBand( _domain_, _range_) [​](https://d3js.org/d3-scale/band\#scaleBand)

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Constructs a new band scale with the specified [_domain_](https://d3js.org/d3-scale/band#band_domain) and [_range_](https://d3js.org/d3-scale/band#band_range), no [padding](https://d3js.org/d3-scale/band#band_padding), no [rounding](https://d3js.org/d3-scale/band#band_round) and center [alignment](https://d3js.org/d3-scale/band#band_align).

js

```
const x = d3.scaleBand(["a", "b", "c"], [0, 960]);
```

If a single argument is specified, it is interpreted as the _range_. If _domain_ is not specified, it defaults to the empty domain. If _range_ is not specified, it defaults to the unit range \[0, 1\].

## _band_( _value_) [​](https://d3js.org/d3-scale/band\#_band)

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Given a _value_ in the input [domain](https://d3js.org/d3-scale/band#band_domain), returns the start of the corresponding band derived from the output [range](https://d3js.org/d3-scale/band#band_range).

js

```
const x = d3.scaleBand(["a", "b", "c"], [0, 960]);
x("a"); // 0
x("b"); // 320
x("c"); // 640
x("d"); // undefined
```

If the given _value_ is not in the scale’s domain, returns undefined.

## _band_.domain( _domain_) [​](https://d3js.org/d3-scale/band\#band_domain)

Domain:

abcdef

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _domain_ is specified, sets the domain to the specified array of values and returns this scale.

js

```
const x = d3.scaleBand([0, 960]).domain(["a", "b", "c", "d", "e", "f"]);
```

The first element in _domain_ will be mapped to the first band, the second domain value to the second band, and so on. Domain values are stored internally in an [InternMap](https://d3js.org/d3-array/intern) from primitive value to index; the resulting index is then used to determine the band. Thus, a band scale’s values must be coercible to a primitive value, and the primitive domain value uniquely identifies the corresponding band. If _domain_ is not specified, this method returns the current domain.

## _band_.range( _range_) [​](https://d3js.org/d3-scale/band\#band_range)

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _range_ is specified, sets the scale’s range to the specified two-element array of numbers and returns this scale.

js

```
const x = d3.scaleBand().range([0, 960]);
```

If the elements in the given array are not numbers, they will be coerced to numbers. If _range_ is not specified, returns the scale’s current range, which defaults to \[0, 1\].

## _band_.rangeRound( _range_) [​](https://d3js.org/d3-scale/band\#band_rangeRound)

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Sets the scale’s [_range_](https://d3js.org/d3-scale/band#band_range) to the specified two-element array of numbers while also enabling [rounding](https://d3js.org/d3-scale/band#band_round); returns this scale.

js

```
const x = d3.scaleBand().rangeRound([0, 960]);
```

This is a convenience method equivalent to:

js

```
band.range(range).round(true)
```

Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the [shape-rendering](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering) “crispEdges” styles.

## _band_.round( _round_) [​](https://d3js.org/d3-scale/band\#band_round)

Round:

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _round_ is specified, enables or disables rounding accordingly and returns this scale.

js

```
const x = d3.scaleBand(["a", "b", "c"], [0, 960]).round(false);
```

If _round_ is not specified, returns whether rounding is enabled.

js

```
x.round() // false
```

If rounding is enabled, the start and stop of each band will be integers. Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the [shape-rendering](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering) “crispEdges” styles. Note that if the width of the domain is not a multiple of the cardinality of the range, there may be leftover unused space, even without padding! Use [_band_.align](https://d3js.org/d3-scale/band#band_align) to specify how the leftover space is distributed.

## _band_.paddingInner( _padding_) [​](https://d3js.org/d3-scale/band\#band_paddingInner)

Inner padding:0.10

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _padding_ is specified, sets the inner padding to the specified number which must be less than or equal to 1 and returns this scale.

js

```
const x = d3.scaleBand(["a", "b", "c"], [0, 960]).paddingInner(0.1);
```

If _padding_ is not specified, returns the current inner padding which defaults to 0.

js

```
x.paddingInner() // 0.1
```

The inner padding specifies the proportion of the range that is reserved for blank space between bands; a value of 0 means no blank space between bands, and a value of 1 means a [bandwidth](https://d3js.org/d3-scale/band#band_bandwidth) of zero.

## _band_.paddingOuter( _padding_) [​](https://d3js.org/d3-scale/band\#band_paddingOuter)

Outer padding:0.10

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _padding_ is specified, sets the outer padding to the specified number which is typically in the range \[0, 1\] and returns this scale.

js

```
const x = d3.scaleBand(["a", "b", "c"], [0, 960]).paddingOuter(0.1);
```

If _padding_ is not specified, returns the current outer padding which defaults to 0.

js

```
x.paddingOuter() // 0.1
```

The outer padding specifies the amount of blank space, in terms of multiples of the [step](https://d3js.org/d3-scale/band#band_step), to reserve before the first band and after the last band.

## _band_.padding( _padding_) [​](https://d3js.org/d3-scale/band\#band_padding)

Padding:0.10

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · A convenience method for setting the [inner](https://d3js.org/d3-scale/band#band_paddingInner) and [outer](https://d3js.org/d3-scale/band#band_paddingOuter) padding to the same _padding_ value.

js

```
const x = d3.scaleBand(["a", "b", "c"], [0, 960]).padding(0.1);
```

If _padding_ is not specified, returns the inner padding.

js

```
x.padding() // 0.1
```

## _band_.align( _align_) [​](https://d3js.org/d3-scale/band\#band_align)

Align:0.50

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _align_ is specified, sets the alignment to the specified value which must be in the range \[0, 1\], and returns this scale.

js

```
const x = d3.scaleBand(["a", "b", "c"], [0, 960]).align(0.5);
```

If _align_ is not specified, returns the current alignment which defaults to 0.5.

js

```
x.align() // 0.5
```

The alignment specifies how outer padding is distributed in the range. A value of 0.5 indicates that the outer padding should be equally distributed before the first band and after the last band; _i.e._, the bands should be centered within the range. A value of 0 or 1 may be used to shift the bands to one side, say to position them adjacent to an axis. For more, [see this explainer](https://observablehq.com/@d3/band-align).

## _band_.bandwidth() [​](https://d3js.org/d3-scale/band\#band_bandwidth)

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Returns the width of each band.

js

```
x.bandwidth() // 50.8235294117647
```

## _band_.step() [​](https://d3js.org/d3-scale/band\#band_step)

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Returns the distance between the starts of adjacent bands.

js

```
x.step() // 63.529411764705884
```

## _band_.copy() [​](https://d3js.org/d3-scale/band\#band_copy)

[Examples](https://observablehq.com/@d3/d3-scaleband) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Returns an exact copy of this scale.

js

```
const x1 = d3.scaleBand(["a", "b", "c"], [0, 960]);
const x2 = x1.copy();
```

Changes to this scale will not affect the returned scale, and vice versa.

## Cyclical Color Schemes
[Skip to content](https://d3js.org/d3-scale-chromatic/cyclical#VPContent)

On this page

# Cyclical schemes [​](https://d3js.org/d3-scale-chromatic/cyclical\#cyclical-schemes)

To create a cyclical continuous color scale using the [Rainbow](https://d3js.org/d3-scale-chromatic/cyclical#interpolateRainbow) color scheme:

js

```
const color = d3.scaleSequential(d3.interpolateRainbow);
```

## interpolateRainbow( _t_) [​](https://d3js.org/d3-scale-chromatic/cyclical\#interpolateRainbow)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/rainbow.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from [d3.interpolateWarm](https://d3js.org/d3-scale-chromatic/sequential#interpolateWarm) scale from \[0.0, 0.5\] followed by the [d3.interpolateCool](https://d3js.org/d3-scale-chromatic/sequential#interpolateCool) scale from \[0.5, 1.0\], thus implementing the cyclical [less-angry rainbow](https://observablehq.com/@mbostock/sinebow) color scheme.

## interpolateSinebow( _t_) [​](https://d3js.org/d3-scale-chromatic/cyclical\#interpolateSinebow)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/sinebow.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “sinebow” color scheme by [Jim Bumgardner](https://krazydad.com/tutorials/makecolors.php) and [Charlie Loyd](http://basecase.org/env/on-rainbows).

## Interning Values in D3
[Skip to content](https://d3js.org/d3-array/intern#VPContent)

On this page

# Interning values [​](https://d3js.org/d3-array/intern\#interning-values)

The [InternMap](https://d3js.org/d3-array/intern#InternMap) and [InternSet](https://d3js.org/d3-array/intern#InternSet) classes extend the native JavaScript Map and Set classes, respectively, allowing Dates and other non-primitive keys by bypassing the [SameValueZero algorithm](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) when determining key equality. [d3.group](https://d3js.org/d3-array/group#group), [d3.rollup](https://d3js.org/d3-array/group#rollup) and [d3.index](https://d3js.org/d3-array/group#index) use an InternMap rather than a native Map.

## new InternMap( _iterable_, _key_) [​](https://d3js.org/d3-array/intern\#InternMap)

js

```
const valueByDate = new d3.InternMap([\
  [new Date("2021-01-01"), 42],\
  [new Date("2022-01-01"), 12],\
  [new Date("2023-01-01"), 45]\
]);
```

[Examples](https://observablehq.com/@mbostock/internmap) · [Source](https://github.com/mbostock/internmap/blob/main/src/index.js) · Constructs a new Map given the specified _iterable_ of \[ _key_, _value_\] entries. The keys are interned using the specified _key_ function which defaults to [_object_.valueOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf) for non-primitive values. For example, to retrieve a value keyed by a given date:

js

```
valueByDate.get(new Date("2022-01-01")) // 12
```

## new InternSet( _iterable_, _key_) [​](https://d3js.org/d3-array/intern\#InternSet)

js

```
const dates = new d3.InternSet([\
  new Date("2021-01-01"),\
  new Date("2022-01-01"),\
  new Date("2023-01-01")\
]);
```

[Examples](https://observablehq.com/@mbostock/internmap) · [Source](https://github.com/mbostock/internmap/blob/main/src/index.js) · Constructs a new Set given the specified _iterable_ of values. The values are interned using the specified _key_ function which defaults to [_object_.valueOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf) for non-primitive values. For example, to query for a given date:

js

```
dates.has(new Date("2022-01-01")) // true
```

## Azimuthal Projections
[Skip to content](https://d3js.org/d3-geo/azimuthal#VPContent)

On this page

# Azimuthal projections [​](https://d3js.org/d3-geo/azimuthal\#azimuthal-projections)

Azimuthal projections project the sphere directly onto a plane.

## geoAzimuthalEqualArea() [​](https://d3js.org/d3-geo/azimuthal\#geoAzimuthalEqualArea)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/azimuthalEqualArea.js) · The azimuthal equal-area projection.

## geoAzimuthalEquidistant() [​](https://d3js.org/d3-geo/azimuthal\#geoAzimuthalEquidistant)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/azimuthalEquidistant.js) · The azimuthal equidistant projection.

## geoGnomonic() [​](https://d3js.org/d3-geo/azimuthal\#geoGnomonic)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/gnomonic.js) · The gnomonic projection.

## geoOrthographic() [​](https://d3js.org/d3-geo/azimuthal\#geoOrthographic)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/orthographic.js) · The orthographic projection.

## geoStereographic() [​](https://d3js.org/d3-geo/azimuthal\#geoStereographic)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/stereographic.js) · The stereographic projection.

## D3.js Stacked Charts
[Skip to content](https://d3js.org/d3-shape/stack#VPContent)

On this page

# Stacks [​](https://d3js.org/d3-shape/stack\#stacks)

[Examples](https://observablehq.com/@d3/stacked-bar-chart/2) · Stacking converts lengths into contiguous position intervals. For example, a bar chart of monthly sales might be broken down into a multi-series bar chart by category, stacking bars vertically and applying a categorical color encoding. Stacked charts can show overall value and per-category value simultaneously; however, it is typically harder to compare across categories as only the bottom layer of the stack is aligned. So, chose the [stack order](https://d3js.org/d3-shape/stack#stack_order) carefully, and consider a [streamgraph](https://d3js.org/d3-shape/stack#stackOffsetWiggle). (See also [grouped charts](https://observablehq.com/@d3/grouped-bar-chart/2).)

Like the [pie generator](https://d3js.org/d3-shape/pie), the stack generator does not produce a shape directly. Instead it computes positions which you can then pass to an [area generator](https://d3js.org/d3-shape/area) or use directly, say to position bars.

## stack() [​](https://d3js.org/d3-shape/stack\#stack)

[Source](https://github.com/d3/d3-shape/blob/main/src/stack.js) · Constructs a new stack generator with the default settings. See [_stack_](https://d3js.org/d3-shape/stack#_stack) for usage.

## _stack_( _data_, ... _arguments_) [​](https://d3js.org/d3-shape/stack\#_stack)

[Source](https://github.com/d3/d3-shape/blob/main/src/stack.js) · Generates a stack for the given array of _data_ and returns an array representing each series. Any additional _arguments_ are arbitrary; they are propagated to accessors along with the `this` object.

For example, consider this tidy table of monthly fruit sales:

| date | fruit | sales |
| --- | --- | --- |
| 1/2015 | apples | 3840 |
| 1/2015 | bananas | 1920 |
| 1/2015 | cherries | 960 |
| 1/2015 | durians | 400 |
| 2/2015 | apples | 1600 |
| 2/2015 | bananas | 1440 |
| 2/2015 | cherries | 960 |
| 2/2015 | durians | 400 |
| 3/2015 | apples | 640 |
| 3/2015 | bananas | 960 |
| 3/2015 | cherries | 640 |
| 3/2015 | durians | 400 |
| 4/2015 | apples | 320 |
| 4/2015 | bananas | 480 |
| 4/2015 | cherries | 640 |
| 4/2015 | durians | 400 |

This could be represented in JavaScript as an array of objects, perhaps parsed from [CSV](https://d3js.org/d3-dsv):

js

```
const data = [\
  {date: new Date("2015-01-01"), fruit: "apples", sales: 3840},\
  {date: new Date("2015-01-01"), fruit: "bananas", sales: 1920},\
  {date: new Date("2015-01-01"), fruit: "cherries", sales: 960},\
  {date: new Date("2015-01-01"), fruit: "durians", sales: 400},\
  {date: new Date("2015-02-01"), fruit: "apples", sales: 1600},\
  {date: new Date("2015-02-01"), fruit: "bananas", sales: 1440},\
  {date: new Date("2015-02-01"), fruit: "cherries", sales: 960},\
  {date: new Date("2015-02-01"), fruit: "durians", sales: 400},\
  {date: new Date("2015-03-01"), fruit: "apples", sales: 640},\
  {date: new Date("2015-03-01"), fruit: "bananas", sales: 960},\
  {date: new Date("2015-03-01"), fruit: "cherries", sales: 640},\
  {date: new Date("2015-03-01"), fruit: "durians", sales: 400},\
  {date: new Date("2015-04-01"), fruit: "apples", sales: 320},\
  {date: new Date("2015-04-01"), fruit: "bananas", sales: 480},\
  {date: new Date("2015-04-01"), fruit: "cherries", sales: 640},\
  {date: new Date("2015-04-01"), fruit: "durians", sales: 400}\
];
```

To compute the stacked series (a series, or layer, for each _fruit_; and a stack, or column, for each _date_), we can [index](https://d3js.org/d3-array/group#index) the data by _date_ and then _fruit_, compute the distinct _fruit_ names across the data set, and lastly get the _sales_ value for each _date_ and _fruit_.

js

```
const series = d3.stack()
    .keys(d3.union(data.map(d => d.fruit))) // apples, bananas, cherries, …
    .value(([, group], key) => group.get(key).sales)
  (d3.index(data, d => d.date, d => d.fruit));
```

TIP

See [union](https://d3js.org/d3-array/sets#union) and [index](https://d3js.org/d3-array/group#index) from d3-array.

The resulting array has one element per _series_. Each series has one point per month, and each point has a lower and upper value defining the baseline and topline:

js

```
[\
  [[   0, 3840], [   0, 1600], [   0,  640], [   0,  320]], // apples\
  [[3840, 5760], [1600, 3040], [ 640, 1600], [ 320,  800]], // bananas\
  [[5760, 6720], [3040, 4000], [1600, 2240], [ 800, 1440]], // cherries\
  [[6720, 7120], [4000, 4400], [2240, 2640], [1440, 1840]]  // durians\
]
```

Each series in then typically passed to an [area generator](https://d3js.org/d3-shape/area) to render an area chart, or used to construct rectangles for a bar chart.

js

```
svg.append("g")
  .selectAll("g")
  .data(series)
  .join("g")
    .attr("fill", d => color(d.key))
  .selectAll("rect")
  .data(D => D)
  .join("rect")
    .attr("x", d => x(d.data[0]))
    .attr("y", d => y(d[1]))
    .attr("height", d => y(d[0]) - y(d[1]))
    .attr("width", x.bandwidth());
```

The series are determined by the [keys accessor](https://d3js.org/d3-shape/stack#stack_keys); each series _i_ in the returned array corresponds to the _i_ th key. Each series is an array of points, where each point _j_ corresponds to the _j_ th element in the input _data_. Lastly, each point is represented as an array \[ _y0_, _y1_\] where _y0_ is the lower value (baseline) and _y1_ is the upper value (topline); the difference between _y0_ and _y1_ corresponds to the computed [value](https://d3js.org/d3-shape/stack#stack_value) for this point. The key for each series is available as _series_.key, and the [index](https://d3js.org/d3-shape/stack#stack_order) as _series_.index. The input data element for each point is available as _point_.data.

## _stack_.keys( _keys_) [​](https://d3js.org/d3-shape/stack\#stack_keys)

[Source](https://github.com/d3/d3-shape/blob/main/src/stack.js) · If _keys_ is specified, sets the keys accessor to the specified function or array and returns this stack generator.

js

```
const stack = d3.stack().keys(["apples", "bananas", "cherries", "durians"]);
```

If _keys_ is not specified, returns the current keys accessor.

js

```
stack.keys() // () => ["apples", "bananas", "cherries", "durians"]
```

The keys accessor defaults to the empty array. A series (layer) is [generated](https://d3js.org/d3-shape/stack#_stack) for each key. Keys are typically strings, but they may be arbitrary values; see [InternMap](https://d3js.org/d3-array/intern). The series’ key is passed to the [value accessor](https://d3js.org/d3-shape/stack#stack_value), along with each data point, to compute the point’s value.

## _stack_.value( _value_) [​](https://d3js.org/d3-shape/stack\#stack_value)

[Source](https://github.com/d3/d3-shape/blob/main/src/stack.js) · If _value_ is specified, sets the value accessor to the specified function or number and returns this stack generator.

js

```
const stack = d3.stack().value((d, key) => d[key]);
```

If _value_ is not specified, returns the current value accessor.

js

```
stack.value() // (d, key) => d[key]
```

The value accessor defaults to:

js

```
function value(d, key) {
  return d[key];
}
```

CAUTION

The default value accessor assumes that the input data is an array of objects exposing named properties with numeric values. This is a “wide” rather than “tidy” representation of data and is no longer recommended. See [_stack_](https://d3js.org/d3-shape/stack#_stack) for an example using tidy data.

## _stack_.order( _order_) [​](https://d3js.org/d3-shape/stack\#stack_order)

[Source](https://github.com/d3/d3-shape/blob/main/src/stack.js) · If _order_ is specified, sets the order accessor to the specified function or array and returns this stack generator.

js

```
const stack = d3.stack().order(d3.stackOrderNone);
```

If _order_ is a function, it is passed the generated series array and must return an array of numeric indexes representing the stack order. For example, to use reverse key order:

js

```
const stack = d3.stack().order(series => d3.range(series.length).reverse());
```

The stack order is computed prior to the [offset](https://d3js.org/d3-shape/stack#stack_offset); thus, the lower value for all points is zero at the time the order is computed. The index attribute for each series is also not set until after the order is computed.

If _order_ is not specified, returns the current order accessor.

js

```
stack.order() // d3.stackOrderNone
```

The order accessor defaults to [stackOrderNone](https://d3js.org/d3-shape/stack#stackOrderNone); this uses the order given by the [key accessor](https://d3js.org/d3-shape/stack#stack_keys). See [stack orders](https://d3js.org/d3-shape/stack#stack-orders) for the built-in orders.

## _stack_.offset( _offset_) [​](https://d3js.org/d3-shape/stack\#stack_offset)

[Source](https://github.com/d3/d3-shape/blob/main/src/stack.js) · If _offset_ is specified, sets the offset accessor to the specified function and returns this stack generator.

js

```
const stack = d3.stack().offset(d3.stackOffsetExpand);
```

The offset function is passed the generated series array and the order index array; it is then responsible for updating the lower and upper values in the series array. See the built-in offsets for a reference implementation.

If _offset_ is not specified, returns the current offset acccesor.

js

```
stack.offset() // d3.stackOffsetExpand
```

The offset accessor defaults to [stackOffsetNone](https://d3js.org/d3-shape/stack#stackOffsetNone); this uses a zero baseline. See [stack offsets](https://d3js.org/d3-shape/stack#stack-offsets) for the built-in offsets.

## Stack orders [​](https://d3js.org/d3-shape/stack\#stack-orders)

Stack orders are typically not used directly, but are instead passed to [_stack_.order](https://d3js.org/d3-shape/stack#stack_order).

### stackOrderAppearance( _series_) [​](https://d3js.org/d3-shape/stack\#stackOrderAppearance)

05101520↑ Annual revenue (billions)197519801985199019952000200520102015

js

```
const stack = d3.stack().order(d3.stackOrderAppearance);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/order/appearance.js) · Returns a series order such that the earliest series (according to the maximum value) is at the bottom.

### stackOrderAscending( _series_) [​](https://d3js.org/d3-shape/stack\#stackOrderAscending)

05101520↑ Annual revenue (billions)197519801985199019952000200520102015

js

```
const stack = d3.stack().order(d3.stackOrderAscending);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/order/ascending.js) · Returns a series order such that the smallest series (according to the sum of values) is at the bottom.

### stackOrderDescending( _series_) [​](https://d3js.org/d3-shape/stack\#stackOrderDescending)

05101520↑ Annual revenue (billions)197519801985199019952000200520102015

js

```
const stack = d3.stack().order(d3.stackOrderDescending);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/order/descending.js) · Returns a series order such that the largest series (according to the sum of values) is at the bottom.

### stackOrderInsideOut( _series_) [​](https://d3js.org/d3-shape/stack\#stackOrderInsideOut)

0510152025↑ Annual revenue (billions)197519801985199019952000200520102015

js

```
const stack = d3.stack().order(d3.stackOrderInsideOut);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/order/insideOut.js) · Returns a series order such that the earliest series (according to the maximum value) are on the inside and the later series are on the outside. This order is recommended for streamgraphs in conjunction with the [wiggle offset](https://d3js.org/d3-shape/stack#stackOffsetWiggle). See [Stacked Graphs — Geometry & Aesthetics](http://leebyron.com/streamgraph/) by Byron & Wattenberg for more information.

### stackOrderNone( _series_) [​](https://d3js.org/d3-shape/stack\#stackOrderNone)

05101520↑ Annual revenue (billions)197519801985199019952000200520102015

js

```
const stack = d3.stack().order(d3.stackOrderNone);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/order/none.js) · Returns the given series order \[0, 1, … _n_ \- 1\] where _n_ is the number of elements in _series_. Thus, the stack order is given by the [key accessor](https://d3js.org/d3-shape/stack#stack_keys).

### stackOrderReverse( _series_) [​](https://d3js.org/d3-shape/stack\#stackOrderReverse)

05101520↑ Annual revenue (billions)197519801985199019952000200520102015

js

```
const stack = d3.stack().order(d3.stackOrderReverse);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/order/reverse.js) · Returns the reverse of the given series order \[ _n_ \- 1, _n_ \- 2, … 0\] where _n_ is the number of elements in _series_. Thus, the stack order is given by the reverse of the [key accessor](https://d3js.org/d3-shape/stack#stack_keys).

## Stack offsets [​](https://d3js.org/d3-shape/stack\#stack-offsets)

Stack offsets are typically not used directly, but are instead passed to [_stack_.offset](https://d3js.org/d3-shape/stack#stack_offset).

### stackOffsetExpand( _series_, _order_) [​](https://d3js.org/d3-shape/stack\#stackOffsetExpand)

020406080100↑ Annual revenue (%)197519801985199019952000200520102015

js

```
const stack = d3.stack().offset(d3.stackOffsetExpand);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/offset/expand.js) · Applies a zero baseline and normalizes the values for each point such that the topline is always one.

### stackOffsetDiverging( _series_, _order_) [​](https://d3js.org/d3-shape/stack\#stackOffsetDiverging)

−20−10010↑ Annual revenue (billions)197519801985199019952000200520102015

js

```
const stack = d3.stack().offset(d3.stackOffsetDiverging);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/offset/diverging.js) · Positive values are stacked above zero, negative values are [stacked below zero](https://observablehq.com/@d3/diverging-stacked-bar-chart/2), and zero values are stacked at zero.

### stackOffsetNone( _series_, _order_) [​](https://d3js.org/d3-shape/stack\#stackOffsetNone)

05101520↑ Annual revenue (billions)197519801985199019952000200520102015

js

```
const stack = d3.stack().offset(d3.stackOffsetNone);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/offset/none.js) · Applies a zero baseline.

### stackOffsetSilhouette( _series_, _order_) [​](https://d3js.org/d3-shape/stack\#stackOffsetSilhouette)

05101520↑ Annual revenue (billions)197519801985199019952000200520102015

js

```
const stack = d3.stack().offset(d3.stackOffsetSilhouette);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/offset/silhouette.js) · Shifts the baseline down such that the center of the streamgraph is always at zero.

### stackOffsetWiggle( _series_, _order_) [​](https://d3js.org/d3-shape/stack\#stackOffsetWiggle)

0510152025↑ Annual revenue (billions)197519801985199019952000200520102015

js

```
const stack = d3.stack().offset(d3.stackOffsetWiggle);
```

[Source](https://github.com/d3/d3-shape/blob/main/src/offset/wiggle.js) · Shifts the baseline so as to minimize the weighted wiggle of layers. This offset is recommended for streamgraphs in conjunction with the [inside-out order](https://d3js.org/d3-shape/stack#stackOrderInsideOut). See [Stacked Graphs — Geometry & Aesthetics](http://leebyron.com/streamgraph/) by Bryon & Wattenberg for more information.

## D3 Easing Functions
[Skip to content](https://d3js.org/d3-ease#VPContent)

On this page

# d3-ease [​](https://d3js.org/d3-ease\#d3-ease)

[Examples](https://observablehq.com/@d3/easing) · _Easing_ is a method of distorting time to control apparent motion in animation. It is most commonly used for [slow-in, slow-out](https://en.wikipedia.org/wiki/Twelve_basic_principles_of_animation#Slow_in_and_slow_out). By easing time, [animated transitions](https://d3js.org/d3-transition) are smoother and exhibit more plausible motion.

The easing types in this module implement the [ease method](https://d3js.org/d3-ease#_ease) which takes a normalized time _t_ and returns the corresponding “eased” time _tʹ_. Both the normalized time and the eased time are typically in the range \[0,1\], where 0 represents the start of the animation and 1 represents the end; some easing types, such as [easeElastic](https://d3js.org/d3-ease#easeElastic), may return eased times slightly outside this range. A good easing type should return 0 if _t_ = 0 and 1 if _t_ = 1.

These easing types are largely based on work by [Robert Penner](http://robertpenner.com/easing/).

## _ease_( _t_) [​](https://d3js.org/d3-ease\#_ease)

Given the specified normalized time _t_, typically in the range \[0,1\], returns the “eased” time _tʹ_, also typically in \[0,1\]. 0 represents the start of the animation and 1 represents the end. A good implementation returns 0 if _t_ = 0 and 1 if _t_ = 1\. For example, to apply [easeCubic](https://d3js.org/d3-ease#easeCubic) easing:

js

```
const te = d3.easeCubic(t);
```

To apply custom [elastic](https://d3js.org/d3-ease#easeElastic) easing, create your easing function before the animation starts:

js

```
const ease = d3.easeElastic.period(0.4);
```

Then during the animation, apply the easing function:

js

```
const te = ease(t);
```

See also [_transition_.ease](https://d3js.org/d3-transition/timing#transition_ease).

## easeLinear [​](https://d3js.org/d3-ease\#easeLinear)

[Source](https://github.com/d3/d3-ease/blob/main/src/linear.js) · Linear easing; the identity function; _linear_( _t_) returns _t_.

## easePoly [​](https://d3js.org/d3-ease\#easePoly)

[Source](https://github.com/d3/d3-ease/blob/main/src/poly.js) · Alias for [easePolyInOut](https://d3js.org/d3-ease#easePolyInOut).

### easePolyIn [​](https://d3js.org/d3-ease\#easePolyIn)

1234exponent

Polynomial easing; raises _t_ to the specified [exponent](https://d3js.org/d3-ease#easePoly_exponent). If the exponent is not specified, it defaults to 3, equivalent to [easeCubicIn](https://d3js.org/d3-ease#easeCubicIn).

### easePolyOut [​](https://d3js.org/d3-ease\#easePolyOut)

1234exponent

Reverse polynomial easing; equivalent to 1 - [easePolyIn](https://d3js.org/d3-ease#easePolyIn)(1 - _t_). If the exponent is not specified, it defaults to 3, equivalent to [easeCubicOut](https://d3js.org/d3-ease#easeCubicOut).

### easePolyInOut [​](https://d3js.org/d3-ease\#easePolyInOut)

1234exponent

Symmetric polynomial easing; scales [easePolyIn](https://d3js.org/d3-ease#easePolyIn) for _t_ in 0–0.5 and [easePolyOut](https://d3js.org/d3-ease#easePolyOut) for _t_ in 0.5–1. If the exponent is not specified, it defaults to 3, equivalent to [easeCubic](https://d3js.org/d3-ease#easeCubic).

### easePoly.exponent( _e_) [​](https://d3js.org/d3-ease\#easePoly_exponent)

Exponent:2.00

Returns a new polynomial easing with the specified exponent _e_. For example, to create equivalents of [easeLinear](https://d3js.org/d3-ease#easeLinear), [easeQuad](https://d3js.org/d3-ease#easeQuad), and [easeCubic](https://d3js.org/d3-ease#easeCubic):

js

```
const linear = d3.easePoly.exponent(1);
const quad = d3.easePoly.exponent(2);
const cubic = d3.easePoly.exponent(3);
```

## easeQuad [​](https://d3js.org/d3-ease\#easeQuad)

[Source](https://github.com/d3/d3-ease/blob/main/src/quad.js) · Alias for [easeQuadInOut](https://d3js.org/d3-ease#easeQuadInOut).

### easeQuadIn [​](https://d3js.org/d3-ease\#easeQuadIn)

Quadratic easing; equivalent to [easePolyIn](https://d3js.org/d3-ease#easePolyIn). [exponent](https://d3js.org/d3-ease#easePoly_exponent)(2).

### easeQuadOut [​](https://d3js.org/d3-ease\#easeQuadOut)

Reverse quadratic easing; equivalent to 1 - [easeQuadIn](https://d3js.org/d3-ease#easeQuadIn)(1 - _t_). Also equivalent to [easePolyOut](https://d3js.org/d3-ease#easePolyOut). [exponent](https://d3js.org/d3-ease#easePoly_exponent)(2).

### easeQuadInOut [​](https://d3js.org/d3-ease\#easeQuadInOut)

Symmetric quadratic easing; scales [easeQuadIn](https://d3js.org/d3-ease#easeQuadIn) for _t_ in 0–0.5 and [easeQuadOut](https://d3js.org/d3-ease#easeQuadOut) for _t_ in 0.5–1. Also equivalent to [easePoly](https://d3js.org/d3-ease#easePoly). [exponent](https://d3js.org/d3-ease#easePoly_exponent)(2).

## easeCubic [​](https://d3js.org/d3-ease\#easeCubic)

[Source](https://github.com/d3/d3-ease/blob/main/src/cubic.js) · Alias for [easeCubicInOut](https://d3js.org/d3-ease#easeCubicInOut).

### easeCubicIn [​](https://d3js.org/d3-ease\#easeCubicIn)

Cubic easing; equivalent to [easePolyIn](https://d3js.org/d3-ease#easePolyIn). [exponent](https://d3js.org/d3-ease#easePoly_exponent)(3).

### easeCubicOut [​](https://d3js.org/d3-ease\#easeCubicOut)

Reverse cubic easing; equivalent to 1 - [easeCubicIn](https://d3js.org/d3-ease#easeCubicIn)(1 - _t_). Also equivalent to [easePolyOut](https://d3js.org/d3-ease#easePolyOut). [exponent](https://d3js.org/d3-ease#easePoly_exponent)(3).

### easeCubicInOut [​](https://d3js.org/d3-ease\#easeCubicInOut)

Symmetric cubic easing; scales [easeCubicIn](https://d3js.org/d3-ease#easeCubicIn) for _t_ in 0–0.5 and [easeCubicOut](https://d3js.org/d3-ease#easeCubicOut) for _t_ in 0.5–1. Also equivalent to [easePoly](https://d3js.org/d3-ease#easePoly). [exponent](https://d3js.org/d3-ease#easePoly_exponent)(3).

## easeSin [​](https://d3js.org/d3-ease\#easeSin)

[Source](https://github.com/d3/d3-ease/blob/main/src/sin.js) · Alias for [easeSinInOut](https://d3js.org/d3-ease#easeSinInOut).

### easeSinIn [​](https://d3js.org/d3-ease\#easeSinIn)

Sinusoidal easing; returns sin( _t_).

### easeSinOut [​](https://d3js.org/d3-ease\#easeSinOut)

Reverse sinusoidal easing; equivalent to 1 - [easeSinIn](https://d3js.org/d3-ease#easeSinIn)(1 - _t_).

### easeSinInOut [​](https://d3js.org/d3-ease\#easeSinInOut)

Symmetric sinusoidal easing; scales [easeSinIn](https://d3js.org/d3-ease#easeSinIn) for _t_ in 0–0.5 and [easeSinOut](https://d3js.org/d3-ease#easeSinOut) for _t_ in 0.5–1.

## easeExp [​](https://d3js.org/d3-ease\#easeExp)

[Source](https://github.com/d3/d3-ease/blob/main/src/exp.js) · Alias for [easeExpInOut](https://d3js.org/d3-ease#easeExpInOut).

### easeExpIn [​](https://d3js.org/d3-ease\#easeExpIn)

Exponential easing; raises 2 to the exponent 10 × ( _t_ \- 1).

### easeExpOut [​](https://d3js.org/d3-ease\#easeExpOut)

Reverse exponential easing; equivalent to 1 - [easeExpIn](https://d3js.org/d3-ease#easeExpIn)(1 - _t_).

### easeExpInOut [​](https://d3js.org/d3-ease\#easeExpInOut)

Symmetric exponential easing; scales [easeExpIn](https://d3js.org/d3-ease#easeExpIn) for _t_ in 0–0.5 and [easeExpOut](https://d3js.org/d3-ease#easeExpOut) for _t_ in 0.5–1.

## easeCircle [​](https://d3js.org/d3-ease\#easeCircle)

[Source](https://github.com/d3/d3-ease/blob/main/src/circle.js) · Alias for [easeCircleInOut](https://d3js.org/d3-ease#easeCircleInOut).

### easeCircleIn [​](https://d3js.org/d3-ease\#easeCircleIn)

Circular easing.

### easeCircleOut [​](https://d3js.org/d3-ease\#easeCircleOut)

Reverse circular easing; equivalent to 1 - [easeCircleIn](https://d3js.org/d3-ease#easeCircleIn)(1 - _t_).

### easeCircleInOut [​](https://d3js.org/d3-ease\#easeCircleInOut)

Symmetric circular easing; scales [easeCircleIn](https://d3js.org/d3-ease#easeCircleIn) for _t_ in 0–0.5 and [easeCircleOut](https://d3js.org/d3-ease#easeCircleOut) for _t_ in 0.5–1.

## easeElastic [​](https://d3js.org/d3-ease\#easeElastic)

[Source](https://github.com/d3/d3-ease/blob/main/src/elastic.js) · Alias for [easeElasticOut](https://d3js.org/d3-ease#easeElasticOut).

### easeElasticIn [​](https://d3js.org/d3-ease\#easeElasticIn)

1.01.11.21.31.41.5amplitude

Elastic easing, like a rubber band. The [amplitude](https://d3js.org/d3-ease#easeElastic_amplitude) and [period](https://d3js.org/d3-ease#easeElastic_period) of the oscillation are configurable; if not specified, they default to 1 and 0.3, respectively.

### easeElasticOut [​](https://d3js.org/d3-ease\#easeElasticOut)

1.01.11.21.31.41.5amplitude

Reverse elastic easing; equivalent to 1 - [elasticIn](https://d3js.org/d3-ease#easeElasticIn)(1 - _t_).

### easeElasticInOut [​](https://d3js.org/d3-ease\#easeElasticInOut)

1.01.11.21.31.41.5amplitude

Symmetric elastic easing; scales [elasticIn](https://d3js.org/d3-ease#easeElasticIn) for _t_ in 0–0.5 and [elasticOut](https://d3js.org/d3-ease#easeElasticOut) for _t_ in 0.5–1.

### easeElastic.amplitude( _a_) [​](https://d3js.org/d3-ease\#easeElastic_amplitude)

Amplitude:1.00

Returns a new elastic easing with the specified amplitude _a_. The amplitude _a_ must be greater than or equal to 1.

### easeElastic.period( _p_) [​](https://d3js.org/d3-ease\#easeElastic_period)

Period:0.30

Returns a new elastic easing with the specified period _p_.

## easeBack [​](https://d3js.org/d3-ease\#easeBack)

[Source](https://github.com/d3/d3-ease/blob/main/src/back.js) · Alias for [easeBackInOut](https://d3js.org/d3-ease#easeBackInOut).

### easeBackIn [​](https://d3js.org/d3-ease\#easeBackIn)

0.51.01.52.02.53.0overshoot

[Anticipatory](https://en.wikipedia.org/wiki/12_basic_principles_of_animation#Anticipation) easing like a dancer bending her knees before jumping off the floor. The degree of [overshoot](https://d3js.org/d3-ease#easeBack_overshoot) is configurable; if not specified, it defaults to 1.70158.

### easeBackOut [​](https://d3js.org/d3-ease\#easeBackOut)

0.51.01.52.02.53.0overshoot

Reverse anticipatory easing; equivalent to 1 - [easeBackIn](https://d3js.org/d3-ease#easeBackIn)(1 - _t_).

### easeBackInOut [​](https://d3js.org/d3-ease\#easeBackInOut)

0.51.01.52.02.53.0overshoot

Symmetric anticipatory easing; scales [easeBackIn](https://d3js.org/d3-ease#easeBackIn) for _t_ in 0–0.5 and [easeBackOut](https://d3js.org/d3-ease#easeBackOut) for _t_ in 0.5–1.

### easeBack.overshoot( _s_) [​](https://d3js.org/d3-ease\#easeBack_overshoot)

Overshoot:1.70

Returns a new back easing with the specified overshoot _s_.

## easeBounce [​](https://d3js.org/d3-ease\#easeBounce)

[Source](https://github.com/d3/d3-ease/blob/main/src/bounce.js) · Alias for [easeBounceOut](https://d3js.org/d3-ease#easeBounceOut).

### easeBounceIn [​](https://d3js.org/d3-ease\#easeBounceIn)

Bounce easing, like a rubber ball.

### easeBounceOut [​](https://d3js.org/d3-ease\#easeBounceOut)

Reverse bounce easing; equivalent to 1 - [easeBounceIn](https://d3js.org/d3-ease#easeBounceIn)(1 - _t_).

### easeBounceInOut [​](https://d3js.org/d3-ease\#easeBounceInOut)

Symmetric bounce easing; scales [easeBounceIn](https://d3js.org/d3-ease#easeBounceIn) for _t_ in 0–0.5 and [easeBounceOut](https://d3js.org/d3-ease#easeBounceOut) for _t_ in 0.5–1.

## Value Interpolation
[Skip to content](https://d3js.org/d3-interpolate/value#VPContent)

On this page

# Value interpolation [​](https://d3js.org/d3-interpolate/value\#value-interpolation)

These are the most general interpolators, suitable for most values.

## interpolate( _a_, _b_) [​](https://d3js.org/d3-interpolate/value\#interpolate)

[Examples](https://observablehq.com/@d3/d3-interpolate) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/value.js) · Returns an interpolator between the two arbitrary values _a_ and _b_.

js

```
d3.interpolate("red", "blue")(0.5) // "rgb(128, 0, 128)"
```

The interpolator implementation is based on the type of the end value _b_, using the following algorithm:

1. If _b_ is null, undefined or a boolean, use the constant _b_.
2. If _b_ is a number, use [interpolateNumber](https://d3js.org/d3-interpolate/value#interpolateNumber).
3. If _b_ is a [color](https://d3js.org/d3-color#color) or a string coercible to a color, use [interpolateRgb](https://d3js.org/d3-interpolate/color#interpolateRgb).
4. If _b_ is a [date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), use [interpolateDate](https://d3js.org/d3-interpolate/value#interpolateDate).
5. If _b_ is a string, use [interpolateString](https://d3js.org/d3-interpolate/value#interpolateString).
6. If _b_ is a [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) of numbers, use [interpolateNumberArray](https://d3js.org/d3-interpolate/value#interpolateNumberArray).
7. If _b_ is a generic [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray), use [interpolateArray](https://d3js.org/d3-interpolate/value#interpolateArray).
8. If _b_ is coercible to a number, use [interpolateNumber](https://d3js.org/d3-interpolate/value#interpolateNumber).
9. Use [interpolateObject](https://d3js.org/d3-interpolate/value#interpolateObject).

Based on the chosen interpolator, _a_ is coerced to the suitable corresponding type.

## interpolateNumber( _a_, _b_) [​](https://d3js.org/d3-interpolate/value\#interpolateNumber)

[Examples](https://observablehq.com/@d3/d3-interpolatenumber) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/number.js) · Returns an interpolator between the two numbers _a_ and _b_.

js

```
d3.interpolateNumber(20, 620)(0.8) // 500
```

The returned interpolator is equivalent to:

js

```
function interpolator(t) {
  return a * (1 - t) + b * t;
}
```

CAUTION

Avoid interpolating to or from the number zero when the interpolator is used to generate a string. When very small values are stringified, they may be converted to scientific notation, which is an invalid attribute or style property value in older browsers. For example, the number `0.0000001` is converted to the string `"1e-7"`. This is particularly noticeable with interpolating opacity. To avoid scientific notation, start or end the transition at 1e-6: the smallest value that is not stringified in scientific notation.

## interpolateRound( _a_, _b_) [​](https://d3js.org/d3-interpolate/value\#interpolateRound)

[Examples](https://observablehq.com/@d3/d3-interpolatenumber) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/round.js) · Returns an interpolator between the two numbers _a_ and _b_.

js

```
d3.interpolateRound(20, 620)(0.821) // 513
```

The interpolator is similar to [interpolateNumber](https://d3js.org/d3-interpolate/value#interpolateNumber) except it will round the resulting value to the nearest integer.

## interpolateString( _a_, _b_) [​](https://d3js.org/d3-interpolate/value\#interpolateString)

[Examples](https://observablehq.com/@d3/d3-interpolatestring) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/string.js) · Returns an interpolator between the two strings _a_ and _b_.

js

```
d3.interpolateString("20px", "32px")(0.5) // "26px"
```

The string interpolator finds numbers embedded in _a_ and _b_, where each number is of the form understood by JavaScript. A few examples of numbers that will be detected within a string: `-1`, `42`, `3.14159`, and `6.0221413e+23`.

For each number embedded in _b_, the interpolator will attempt to find a corresponding number in _a_. If a corresponding number is found, a numeric interpolator is created using [interpolateNumber](https://d3js.org/d3-interpolate/value#interpolateNumber). The remaining parts of the string _b_ are used as a template: the static parts of the string _b_ remain constant for the interpolation, with the interpolated numeric values embedded in the template.

For example, if _a_ is `"300 12px sans-serif"`, and _b_ is `"500 36px Comic-Sans"`, two embedded numbers are found. The remaining static parts (of string _b_) are a space between the two numbers ( `" "`), and the suffix ( `"px Comic-Sans"`). The result of the interpolator at _t_ = 0.5 is `"400 24px Comic-Sans"`.

## interpolateDate( _a_, _b_) [​](https://d3js.org/d3-interpolate/value\#interpolateDate)

[Examples](https://observablehq.com/@d3/d3-interpolatedate) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/date.js) · Returns an interpolator between the two [dates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) _a_ and _b_.

js

```
d3.interpolateDate(new Date("2014-01-01"), new Date("2024-01-01"))(0.5) // 2019-01-01
```

CAUTION

**No defensive copy** of the returned date is created; the same Date instance is returned for every evaluation of the interpolator. No copy is made for performance reasons, as interpolators are often part of the inner loop of [animated transitions](https://d3js.org/d3-transition).

## interpolateArray( _a_, _b_) [​](https://d3js.org/d3-interpolate/value\#interpolateArray)

[Examples](https://observablehq.com/@d3/d3-interpolateobject) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/array.js) · Returns an interpolator between the two arrays _a_ and _b_.

js

```
d3.interpolateArray([0, 0, 0], [1, 2, 3])(0.5) // [0.5, 1, 1.5]
```

If _b_ is a typed array (e.g., Float64Array), [interpolateNumberArray](https://d3js.org/d3-interpolate/value#interpolateNumberArray) is called instead.

Internally, an array template is created that is the same length as _b_. For each element in _b_, if there exists a corresponding element in _a_, a generic interpolator is created for the two elements using [interpolate](https://d3js.org/d3-interpolate/value#interpolate). If there is no such element, the static value from _b_ is used in the template. Then, for the given parameter _t_, the template’s embedded interpolators are evaluated. The updated array template is then returned.

For example, if _a_ is the array `[0, 1]` and _b_ is the array `[1, 10, 100]`, then the result of the interpolator for _t_ = 0.5 is the array `[0.5, 5.5, 100]`.

CAUTION

**No defensive copy** of the template array is created; modifications of the returned array may adversely affect subsequent evaluation of the interpolator. No copy is made for performance reasons; interpolators are often part of the inner loop of [animated transitions](https://d3js.org/d3-transition).

## interpolateNumberArray( _a_, _b_) [​](https://d3js.org/d3-interpolate/value\#interpolateNumberArray)

[Examples](https://observablehq.com/@d3/d3-interpolatenumberarray) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/numberArray.js) · Returns an interpolator between the two arrays of numbers _a_ and _b_.

js

```
d3.interpolateNumberArray([0, 1], Float64Array.of(1, 3))(0.5) // [0.5, 2]
```

Internally, an array template is created that is the same type and length as _b_. For each element in _b_, if there exists a corresponding element in _a_, the values are directly interpolated in the array template. If there is no such element, the static value from _b_ is copied. The updated array template is then returned.

CAUTION

**No defensive copy** is made of the template array and the arguments _a_ and _b_; modifications of these arrays may affect subsequent evaluation of the interpolator.

## interpolateObject( _a_, _b_) [​](https://d3js.org/d3-interpolate/value\#interpolateObject)

[Examples](https://observablehq.com/@d3/d3-interpolateobject) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/object.js) · Returns an interpolator between the two objects _a_ and _b_.

js

```
d3.interpolateObject({x: 0, y: 1}, {x: 1, y: 10, z: 100})(0.5) // {x: 0.5, y: 5.5, z: 100}
```

Internally, an object template is created that has the same properties as _b_. For each property in _b_, if there exists a corresponding property in _a_, a generic interpolator is created for the two elements using [interpolate](https://d3js.org/d3-interpolate/value#interpolate). If there is no such property, the static value from _b_ is used in the template. Then, for the given parameter _t_, the template's embedded interpolators are evaluated and the updated object template is then returned.

For example, if _a_ is the object `{x: 0, y: 1}` and _b_ is the object `{x: 1, y: 10, z: 100}`, the result of the interpolator for _t_ = 0.5 is the object `{x: 0.5, y: 5.5, z: 100}`.

Object interpolation is particularly useful for _dataspace interpolation_, where data is interpolated rather than attribute values. For example, you can interpolate an object which describes an arc in a pie chart, and then use [arc](https://d3js.org/d3-shape/arc) to compute the new SVG path data.

CAUTION

**No defensive copy** of the template object is created; modifications of the returned object may adversely affect subsequent evaluation of the interpolator. No copy is made for performance reasons; interpolators are often part of the inner loop of [animated transitions](https://d3js.org/d3-transition).

## interpolateBasis( _values_) [​](https://d3js.org/d3-interpolate/value\#interpolateBasis)

[Examples](https://observablehq.com/@d3/d3-interpolatebasis) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/basis.js) · Returns a uniform nonrational B-spline interpolator through the specified array of _values_, which must be numbers.

js

```
d3.interpolateBasis([0, 0.1, 0.4, 1])(0.5) // 0.2604166666666667
```

Implicit control points are generated such that the interpolator returns _values_\[0\] at _t_ = 0 and _values_\[ _values_.length - 1\] at _t_ = 1\. See also [curveBasis](https://d3js.org/d3-shape/curve#curveBasis) and [interpolateRgbBasis](https://d3js.org/d3-interpolate/color#interpolateRgbBasis).

## interpolateBasisClosed( _values_) [​](https://d3js.org/d3-interpolate/value\#interpolateBasisClosed)

[Examples](https://observablehq.com/@d3/d3-interpolatebasis) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/basisClosed.js) · Returns a uniform nonrational B-spline interpolator through the specified array of _values_, which must be numbers.

js

```
d3.interpolateBasisClosed([0, 0.1, 0.4, 1])(0.5) // 0.45
```

The control points are implicitly repeated such that the resulting one-dimensional spline has cyclical C² continuity when repeated around _t_ in \[0,1\]. See also [curveBasisClosed](https://d3js.org/d3-shape/curve#curveBasisClosed) and [interpolateRgbBasisClosed](https://d3js.org/d3-interpolate/color#interpolateRgbBasisClosed).

## interpolateDiscrete( _values_) [​](https://d3js.org/d3-interpolate/value\#interpolateDiscrete)

[Examples](https://observablehq.com/@d3/d3-interpolatediscrete) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/discrete.js) · Returns a discrete interpolator for the given array of _values_.

js

```
d3.interpolateDiscrete(["red", "blue", "green"])(0.5) // "blue"
```

The returned interpolator maps _t_ in \[0, 1 / _n_) to _values_\[0\], _t_ in \[1 / _n_, 2 / _n_) to _values_\[1\], and so on, where _n_ = _values_.length. In effect, this is a lightweight [quantize scale](https://d3js.org/d3-scale/quantize) with a fixed domain of \[0, 1\].\
\
## quantize( _interpolator_, _n_) [​](https://d3js.org/d3-interpolate/value\#quantize)\
\
[Examples](https://observablehq.com/@d3/d3-quantize) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/quantize.js) · Returns _n_ uniformly-spaced samples from the specified _interpolator_, where _n_ is an integer greater than one.\
\
js\
\
```\
d3.quantize(d3.interpolate("red", "blue"), 4) // ["rgb(255, 0, 0)", "rgb(170, 0, 85)", "rgb(85, 0, 170)", "rgb(0, 0, 255)"]\
```\
\
The first sample is always at _t_ = 0, and the last sample is always at _t_ = 1\. This can be useful in generating a fixed number of samples from a given interpolator, such as to derive the range of a [quantize scale](https://d3js.org/d3-scale/quantize) from a [continuous interpolator](https://d3js.org/d3-scale-chromatic/sequential#interpolateWarm).\
\
CAUTION\
\
This method will not work with interpolators that do not return defensive copies of their output, such as [interpolateArray](https://d3js.org/d3-interpolate/value#interpolateArray), [interpolateDate](https://d3js.org/d3-interpolate/value#interpolateDate) and [interpolateObject](https://d3js.org/d3-interpolate/value#interpolateObject). For those interpolators, you must wrap the interpolator and create a copy for each returned value.\
\
## piecewise( _interpolate_, _values_) [​](https://d3js.org/d3-interpolate/value\#piecewise)\
\
[Examples](https://observablehq.com/@d3/d3-piecewise) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/piecewise.js) · Returns a piecewise interpolator, composing interpolators for each adjacent pair of _values_.\
\
js\
\
```\
d3.piecewise(d3.interpolateRgb.gamma(2.2), ["red", "green", "blue"])\
```\
\
If _interpolate_ is not specified, defaults to [interpolate](https://d3js.org/d3-interpolate/value#interpolate).\
\
js\
\
```\
d3.piecewise(["red", "green", "blue"])\
```\
\
The returned interpolator maps _t_ in \[0, 1 / ( _n_ \- 1)\] to _interpolate_( _values_\[0\], _values_\[1\]), _t_ in \[1 / ( _n_ \- 1), 2 / ( _n_ \- 1)\] to _interpolate_( _values_\[1\], _values_\[2\]), and so on, where _n_ = _values_.length. In effect, this is a lightweight [linear scale](https://d3js.org/d3-scale/linear).

## D3.js Scales Overview
[Skip to content](https://d3js.org/d3-scale#VPContent)

Return to top

# d3-scale [​](https://d3js.org/d3-scale\#d3-scale)

Scales map a dimension of abstract data to a visual representation. Although most often used for encoding data as position, say to map time and temperature to a horizontal and vertical position in a scatterplot, scales can represent virtually any visual encoding, such as color, stroke width, or symbol size. Scales can also be used with virtually any type of data, such as named categorical data or discrete data that requires sensible breaks.

See one of:

- [Linear scales](https://d3js.org/d3-scale/linear) \- for quantitative data
- [Time scales](https://d3js.org/d3-scale/time) \- for time-series data
- [Pow scales](https://d3js.org/d3-scale/pow) \- for quantitative data (that has a wide range)
- [Log scales](https://d3js.org/d3-scale/log) \- for quantitative data (that has a wide range)
- [Symlog scales](https://d3js.org/d3-scale/symlog) \- for quantitative data (that has a wide range)
- [Ordinal scales](https://d3js.org/d3-scale/ordinal) \- for categorical or ordinal data
- [Band scales](https://d3js.org/d3-scale/band) \- for categorical or ordinal data as a position encoding
- [Point scales](https://d3js.org/d3-scale/point) \- for categorical or ordinal data as a position encoding
- [Sequential scales](https://d3js.org/d3-scale/sequential) \- for quantitative data as a sequential color encoding
- [Diverging scales](https://d3js.org/d3-scale/diverging) \- for quantitative data as a diverging color encoding
- [Quantile scales](https://d3js.org/d3-scale/quantile) \- for quantitative data as a discrete encoding
- [Quantize scales](https://d3js.org/d3-scale/quantize) \- for quantitative data as a discrete encoding
- [Threshold scales](https://d3js.org/d3-scale/threshold) \- for quantitative data as a discrete encoding

For visualizing the scale’s encoding, see [d3-axis](https://d3js.org/d3-axis), as well as [_scale_.ticks](https://d3js.org/d3-scale/linear#linear_ticks) and [_scale_.tickFormat](https://d3js.org/d3-scale/linear#linear_tickFormat). For color schemes, see [d3-scale-chromatic](https://d3js.org/d3-scale-chromatic).

## D3 Delaunay Library
[Skip to content](https://d3js.org/d3-delaunay#VPContent)

Return to top

# d3-delaunay [​](https://d3js.org/d3-delaunay\#d3-delaunay)

This is a fast library for computing the [Voronoi diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) of a set of two-dimensional points. It is based on [Delaunator](https://github.com/mapbox/delaunator), a fast library for computing the [Delaunay triangulation](https://en.wikipedia.org/wiki/Delaunay_triangulation) using [sweep algorithms](https://github.com/mapbox/delaunator/blob/main/README.md#papers). The Voronoi diagram is constructed by connecting the circumcenters of adjacent triangles in the Delaunay triangulation.

See one of:

- [Delaunay triangulations](https://d3js.org/d3-delaunay/delaunay)
- [Voronoi diagrams](https://d3js.org/d3-delaunay/voronoi)

For an interactive explanation of how this library works, see [The Delaunay’s Dual](https://observablehq.com/@mbostock/the-delaunays-dual).

## D3 Time Format
[Skip to content](https://d3js.org/d3-time-format#VPContent)

On this page

# d3-time-format [​](https://d3js.org/d3-time-format\#d3-time-format)

This module provides an approximate JavaScript implementation of the venerable [strptime](http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html) and [strftime](http://pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html) functions from the C standard library, and can be used to parse or format [dates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) in a variety of locale-specific representations. To format a date, create a [formatter](https://d3js.org/d3-time-format#locale_format) from a specifier (a string with the desired format _directives_, indicated by `%`); then pass a date to the formatter, which returns a string. For example, to convert the current date to a human-readable string:

js

```
const formatTime = d3.utcFormat("%B %d, %Y");
formatTime(new Date()); // "May 31, 2023"
```

Likewise, to convert a string back to a date, create a [parser](https://d3js.org/d3-time-format#locale_parse):

js

```
const parseTime = d3.utcParse("%B %d, %Y");
parseTime("June 30, 2015"); // 2023-05-31
```

You can implement more elaborate conditional time formats, too. For example, here’s a multi-scale time format using [time intervals](https://d3js.org/d3-time):

js

```
const formatMillisecond = d3.utcFormat(".%L"),
    formatSecond = d3.utcFormat(":%S"),
    formatMinute = d3.utcFormat("%I:%M"),
    formatHour = d3.utcFormat("%I %p"),
    formatDay = d3.utcFormat("%a %d"),
    formatWeek = d3.utcFormat("%b %d"),
    formatMonth = d3.utcFormat("%B"),
    formatYear = d3.utcFormat("%Y");

function multiFormat(date) {
  return (d3.utcSecond(date) < date ? formatMillisecond
      : d3.utcMinute(date) < date ? formatSecond
      : d3.utcHour(date) < date ? formatMinute
      : d3.utcDay(date) < date ? formatHour
      : d3.utcMonth(date) < date ? (d3.utcWeek(date) < date ? formatDay : formatWeek)
      : d3.utcYear(date) < date ? formatMonth
      : formatYear)(date);
}
```

This module is used by D3 [time scales](https://d3js.org/d3-scale/time) to generate human-readable ticks.

Also see [_date_.toLocaleString](https://observablehq.com/@mbostock/date-formatting).

## timeFormat( _specifier_) [​](https://d3js.org/d3-time-format\#timeFormat)

js

```
d3.timeFormat("%b %d")
```

An alias for [_locale_.format](https://d3js.org/d3-time-format#locale_format) on the [default locale](https://d3js.org/d3-time-format#timeFormatDefaultLocale).

## timeParse( _specifier_) [​](https://d3js.org/d3-time-format\#timeParse)

js

```
d3.timeParse("%b %d")
```

An alias for [_locale_.parse](https://d3js.org/d3-time-format#locale_parse) on the [default locale](https://d3js.org/d3-time-format#timeFormatDefaultLocale).

## utcFormat( _specifier_) [​](https://d3js.org/d3-time-format\#utcFormat)

js

```
d3.utcFormat("%b %d")
```

An alias for [_locale_.utcFormat](https://d3js.org/d3-time-format#locale_utcFormat) on the [default locale](https://d3js.org/d3-time-format#timeFormatDefaultLocale).

## utcParse( _specifier_) [​](https://d3js.org/d3-time-format\#utcParse)

js

```
d3.utcParse("%b %d")
```

An alias for [_locale_.utcParse](https://d3js.org/d3-time-format#locale_utcParse) on the [default locale](https://d3js.org/d3-time-format#timeFormatDefaultLocale).

## isoFormat [​](https://d3js.org/d3-time-format\#isoFormat)

js

```
d3.isoFormat(new Date()) // "2023-05-31T18:17:36.788Z"
```

[Source](https://github.com/d3/d3-time-format/blob/main/src/isoFormat.js) · The full [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) UTC time formatter. Where available, this method will use [Date.toISOString](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toISOString) to format.

## isoParse [​](https://d3js.org/d3-time-format\#isoParse)

js

```
d3.isoParse("2023-05-31T18:17:36.788Z")
```

[Source](https://github.com/d3/d3-time-format/blob/main/src/isoParse.js) · The full [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) UTC time parser. Where available, this method will use the [Date constructor](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date) to parse strings. If you depend on strict validation of the input format according to ISO 8601, you should construct a [UTC parser function](https://d3js.org/d3-time-format#utcParse):

js

```
const strictIsoParse = d3.utcParse("%Y-%m-%dT%H:%M:%S.%LZ");
```

## _locale_.format( _specifier_) [​](https://d3js.org/d3-time-format\#locale_format)

js

```
d3.timeFormat("%b %d")
```

[Source](https://github.com/d3/d3-time-format/blob/main/src/locale.js) · Returns a new formatter for the given string _specifier_. The specifier string may contain the following directives:

- `%a` \- abbreviated weekday name.\*
- `%A` \- full weekday name.\*
- `%b` \- abbreviated month name.\*
- `%B` \- full month name.\*
- `%c` \- the locale’s date and time, such as `%x, %X`.\*
- `%d` \- zero-padded day of the month as a decimal number \[01,31\].
- `%e` \- space-padded day of the month as a decimal number \[ 1,31\]; equivalent to `%_d`.
- `%f` \- microseconds as a decimal number \[000000, 999999\].
- `%g` \- ISO 8601 week-based year without century as a decimal number \[00,99\].
- `%G` \- ISO 8601 week-based year with century as a decimal number.
- `%H` \- hour (24-hour clock) as a decimal number \[00,23\].
- `%I` \- hour (12-hour clock) as a decimal number \[01,12\].
- `%j` \- day of the year as a decimal number \[001,366\].
- `%m` \- month as a decimal number \[01,12\].
- `%M` \- minute as a decimal number \[00,59\].
- `%L` \- milliseconds as a decimal number \[000, 999\].
- `%p` \- either AM or PM.\*
- `%q` \- quarter of the year as a decimal number \[1,4\].
- `%Q` \- milliseconds since UNIX epoch.
- `%s` \- seconds since UNIX epoch.
- `%S` \- second as a decimal number \[00,61\].
- `%u` \- Monday-based (ISO 8601) weekday as a decimal number \[1,7\].
- `%U` \- Sunday-based week of the year as a decimal number \[00,53\].
- `%V` \- ISO 8601 week of the year as a decimal number \[01, 53\].
- `%w` \- Sunday-based weekday as a decimal number \[0,6\].
- `%W` \- Monday-based week of the year as a decimal number \[00,53\].
- `%x` \- the locale’s date, such as `%-m/%-d/%Y`.\*
- `%X` \- the locale’s time, such as `%-I:%M:%S %p`.\*
- `%y` \- year without century as a decimal number \[00,99\].
- `%Y` \- year with century as a decimal number, such as `1999`.
- `%Z` \- time zone offset, such as `-0700`, `-07:00`, `-07`, or `Z`.
- `%%` \- a literal percent sign ( `%`).

Directives marked with an asterisk (\*) may be affected by the [locale definition](https://d3js.org/d3-time-format#timeFormatLocale).

For `%U`, all days in a new year preceding the first Sunday are considered to be in week 0. For `%W`, all days in a new year preceding the first Monday are considered to be in week 0. Week numbers are computed using [_interval_.count](https://d3js.org/d3-time#interval_count). For example, 2015-52 and 2016-00 represent Monday, December 28, 2015, while 2015-53 and 2016-01 represent Monday, January 4, 2016. This differs from the [ISO week date](https://en.wikipedia.org/wiki/ISO_week_date) specification ( `%V`), which uses a more complicated definition!

For `%V`, `%g` and `%G`, per the [strftime man page](http://man7.org/linux/man-pages/man3/strftime.3.html):

> In this system, weeks start on a Monday, and are numbered from 01, for the first week, up to 52 or 53, for the last week. Week 1 is the first week where four or more days fall within the new year (or, synonymously, week 01 is: the first week of the year that contains a Thursday; or, the week that has 4 January in it). If the ISO week number belongs to the previous or next year, that year is used instead.

The `%` sign indicating a directive may be immediately followed by a padding modifier:

- `0` \- zero-padding
- `_` \- space-padding
- `-` \- disable padding

If no padding modifier is specified, the default is `0` for all directives except `%e`, which defaults to `_`. (In some implementations of strftime and strptime, a directive may include an optional field width or precision; this feature is not yet implemented.)

The returned function formats a specified _[date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date)_, returning the corresponding string.

js

```
const formatMonth = d3.timeFormat("%B"),
    formatDay = d3.timeFormat("%A"),
    date = new Date(2014, 4, 1); // Thu May 01 2014 00:00:00 GMT-0700 (PDT)

formatMonth(date); // "May"
formatDay(date); // "Thursday"
```

## _locale_.parse( _specifier_) [​](https://d3js.org/d3-time-format\#locale_parse)

js

```
d3.timeParse("%b %d")
```

[Source](https://github.com/d3/d3-time-format/blob/main/src/locale.js) · Returns a new parser for the given string _specifier_. The specifier string may contain the same directives as [_locale_.format](https://d3js.org/d3-time-format#locale_format). The `%d` and `%e` directives are considered equivalent for parsing.

The returned function parses a specified _string_, returning the corresponding [date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) or null if the string could not be parsed according to this format’s specifier. Parsing is strict: if the specified _string_ does not exactly match the associated specifier, this method returns null. For example, if the associated specifier is `%Y-%m-%dT%H:%M:%SZ`, then the string `"2011-07-01T19:15:28Z"` will be parsed as expected, but `"2011-07-01T19:15:28"`, `"2011-07-01 19:15:28"` and `"2011-07-01"` will return null. (Note that the literal `Z` here is different from the time zone offset directive `%Z`.) If a more flexible parser is desired, try multiple formats sequentially until one returns non-null.

## _locale_.utcFormat( _specifier_) [​](https://d3js.org/d3-time-format\#locale_utcFormat)

js

```
d3.utcFormat("%b %d")
```

[Source](https://github.com/d3/d3-time-format/blob/main/src/locale.js) · Equivalent to [_locale_.format](https://d3js.org/d3-time-format#locale_format), except all directives are interpreted as [Coordinated Universal Time (UTC)](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) rather than local time.

## _locale_.utcParse( _specifier_) [​](https://d3js.org/d3-time-format\#locale_utcParse)

js

```
d3.utcParse("%b %d")
```

[Source](https://github.com/d3/d3-time-format/blob/main/src/locale.js) · Equivalent to [_locale_.parse](https://d3js.org/d3-time-format#locale_parse), except all directives are interpreted as [Coordinated Universal Time (UTC)](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) rather than local time.

## timeFormatLocale( _definition_) [​](https://d3js.org/d3-time-format\#timeFormatLocale)

js

```
const enUs = d3.timeFormatLocale({
  dateTime: "%x, %X",
  date: "%-m/%-d/%Y",
  time: "%-I:%M:%S %p",
  periods: ["AM", "PM"],
  days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});
```

[Source](https://github.com/d3/d3-time-format/blob/main/src/locale.js) · Returns a _locale_ object for the specified _definition_ with [_locale_.format](https://d3js.org/d3-time-format#locale_format), [_locale_.parse](https://d3js.org/d3-time-format#locale_parse), [_locale_.utcFormat](https://d3js.org/d3-time-format#locale_utcFormat), [_locale_.utcParse](https://d3js.org/d3-time-format#locale_utcParse) methods. The _definition_ must include the following properties:

- `dateTime` \- the date and time ( `%c`) format specifier ( _e.g._, `"%a %b %e %X %Y"`).
- `date` \- the date ( `%x`) format specifier ( _e.g._, `"%m/%d/%Y"`).
- `time` \- the time ( `%X`) format specifier ( _e.g._, `"%H:%M:%S"`).
- `periods` \- the A.M. and P.M. equivalents ( _e.g._, `["AM", "PM"]`).
- `days` \- the full names of the weekdays, starting with Sunday.
- `shortDays` \- the abbreviated names of the weekdays, starting with Sunday.
- `months` \- the full names of the months (starting with January).
- `shortMonths` \- the abbreviated names of the months (starting with January).

## timeFormatDefaultLocale( _definition_) [​](https://d3js.org/d3-time-format\#timeFormatDefaultLocale)

js

```
const enUs = d3.timeFormatDefaultLocale({
  dateTime: "%x, %X",
  date: "%-m/%-d/%Y",
  time: "%-I:%M:%S %p",
  periods: ["AM", "PM"],
  days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});
```

[Source](https://github.com/d3/d3-time-format/blob/main/src/defaultLocale.js) · Equivalent to [d3.timeFormatLocale](https://d3js.org/d3-time-format#timeFormatLocale), except it also redefines [d3.timeFormat](https://d3js.org/d3-time-format#timeFormat), [d3.timeParse](https://d3js.org/d3-time-format#timeParse), [d3.utcFormat](https://d3js.org/d3-time-format#utcFormat) and [d3.utcParse](https://d3js.org/d3-time-format#utcParse) to the new locale’s [_locale_.format](https://d3js.org/d3-time-format#locale_format), [_locale_.parse](https://d3js.org/d3-time-format#locale_parse), [_locale_.utcFormat](https://d3js.org/d3-time-format#locale_utcFormat) and [_locale_.utcParse](https://d3js.org/d3-time-format#locale_utcParse). If you do not set a default locale, it defaults to [U.S. English](https://github.com/d3/d3-time-format/blob/main/locale/en-US.json).

## Quantile Scales Overview
[Skip to content](https://d3js.org/d3-scale/quantile#VPContent)

On this page

# Quantile scales [​](https://d3js.org/d3-scale/quantile\#quantile-scales)

Quantile scales map a sampled input domain to a discrete range. The domain is considered continuous and thus the scale will accept any reasonable input value; however, the domain is specified as a discrete set of sample values. The number of values in (the cardinality of) the output range determines the number of quantiles that will be computed from the domain. To compute the quantiles, the domain is sorted, and treated as a [population of discrete values](https://en.wikipedia.org/wiki/Quantile#Quantiles_of_a_population); see [quantile](https://d3js.org/d3-array/summarize#quantile). See [this quantile choropleth](https://observablehq.com/@d3/quantile-choropleth) for an example.

## scaleQuantile( _domain_, _range_) [​](https://d3js.org/d3-scale/quantile\#scaleQuantile)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/quantile.js) · Constructs a new quantile scale with the specified [_domain_](https://d3js.org/d3-scale/quantile#quantile_domain) and [_range_](https://d3js.org/d3-scale/quantile#quantile_range).

js

```
const color = d3.scaleQuantile(penguins.map((d) => d.body_mass_g), d3.schemeBlues[5]);
```

If either _domain_ or _range_ is not specified, each defaults to the empty array. The quantile scale is invalid until both a domain and range are specified.

## _quantile_( _value_) [​](https://d3js.org/d3-scale/quantile\#_quantile)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/quantile.js) · Given a _value_ in the input [domain](https://d3js.org/d3-scale/quantile#quantile_domain), returns the corresponding value in the output [range](https://d3js.org/d3-scale/quantile#quantile_range).

js

```
color(3000); // "#eff3ff"
color(4000); // "#6baed6"
color(5000); // "#08519c"
```

## _quantile_.invertExtent( _value_) [​](https://d3js.org/d3-scale/quantile\#quantile_invertExtent)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/quantile.js) · Returns the extent of values in the [domain](https://d3js.org/d3-scale/quantile#quantile_domain) \[ _x0_, _x1_\] for the corresponding _value_ in the [range](https://d3js.org/d3-scale/quantile#quantile_range): the inverse of [_quantile_](https://d3js.org/d3-scale/quantile#_quantile).

js

```
color.invertExtent("#eff3ff"); // [2700, 3475]
color.invertExtent("#6baed6"); // [3800, 4300]
color.invertExtent("#08519c"); // [4950, 6300]
```

This method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse.

## _quantile_.domain( _domain_) [​](https://d3js.org/d3-scale/quantile\#quantile_domain)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/quantile.js) · If _domain_ is specified, sets the domain of the quantile scale to the specified set of discrete numeric values and returns this scale.

js

```
const color = d3.scaleQuantile(d3.schemeBlues[5]);
color.domain(penguins.map((d) => d.body_mass_g));
```

The array must not be empty, and must contain at least one numeric value; NaN, null and undefined values are ignored and not considered part of the sample population. If the elements in the given array are not numbers, they will be coerced to numbers. A copy of the input array is sorted and stored internally.

If _domain_ is not specified, returns the scale’s current domain (the set of observed values).

js

```
color.domain() // [2700, 2850, 2850, 2900, 2900, 2900, 2900, …]
```

## _quantile_.range( _range_) [​](https://d3js.org/d3-scale/quantile\#quantile_range)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/quantile.js) · If _range_ is specified, sets the discrete values in the range.

js

```
const color = d3.scaleQuantile();
color.range(d3.schemeBlues[5]);
```

The array must not be empty, and may contain any type of value. The number of values in (the cardinality, or length, of) the _range_ array determines the number of quantiles that are computed. For example, to compute quartiles, _range_ must be an array of four elements such as \[0, 1, 2, 3\].

If _range_ is not specified, returns the current range.

js

```
color.range() // ["#eff3ff", "#bdd7e7", "#6baed6", "#3182bd", "#08519c"]
```

## _quantile_.quantiles() [​](https://d3js.org/d3-scale/quantile\#quantile_quantiles)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/quantile.js) · Returns the quantile thresholds.

js

```
color.quantiles() // [3475, 3800, 4300, 4950]
```

If the [range](https://d3js.org/d3-scale/quantile#quantile_range) contains _n_ discrete values, the returned array will contain _n_ \- 1 thresholds. Values less than the first threshold are considered in the first quantile; values greater than or equal to the first threshold but less than the second threshold are in the second quantile, and so on. Internally, the thresholds array is used with [bisect](https://d3js.org/d3-array/bisect) to find the output quantile associated with the given input value.

## _quantile_.copy() [​](https://d3js.org/d3-scale/quantile\#quantile_copy)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/quantile.js) · Returns an exact copy of this scale.

js

```
const c1 = d3.scaleQuantile(d3.schemeBlues[5]);
const c2 = c1.copy();
```

Changes to this scale will not affect the returned scale, and vice versa.

## D3.js Ordinal Scales
[Skip to content](https://d3js.org/d3-scale/ordinal#VPContent)

On this page

# Ordinal scales [​](https://d3js.org/d3-scale/ordinal\#ordinal-scales)

Unlike [continuous scales](https://d3js.org/d3-scale/linear), ordinal scales have a discrete domain and range. For example, an ordinal scale might map a set of named categories to a set of colors, or determine the horizontal positions of columns in a column chart.

## scaleOrdinal( _domain_, _range_) [​](https://d3js.org/d3-scale/ordinal\#scaleOrdinal)

[Examples](https://observablehq.com/@d3/d3-scaleordinal) · [Source](https://github.com/d3/d3-scale/blob/main/src/ordinal.js) · Constructs a new ordinal scale with the specified [_domain_](https://d3js.org/d3-scale/ordinal#ordinal_domain) and [_range_](https://d3js.org/d3-scale/ordinal#ordinal_range).

js

```
const color = d3.scaleOrdinal(["a", "b", "c"], ["red", "green", "blue"]);
```

If _domain_ is not specified, it defaults to the empty array. If _range_ is not specified, it defaults to the empty array; an ordinal scale always returns undefined until a non-empty range is defined.

## _ordinal_( _value_) [​](https://d3js.org/d3-scale/ordinal\#_ordinal)

[Examples](https://observablehq.com/@d3/d3-scaleordinal) · [Source](https://github.com/d3/d3-scale/blob/main/src/ordinal.js) · Given a _value_ in the input [domain](https://d3js.org/d3-scale/ordinal#ordinal_domain), returns the corresponding value in the output [range](https://d3js.org/d3-scale/ordinal#ordinal_range).

js

```
color("a") // "red"
```

If the given _value_ is not in the scale’s [domain](https://d3js.org/d3-scale/ordinal#ordinal_domain), returns the [unknown value](https://d3js.org/d3-scale/ordinal#ordinal_unknown); or, if the unknown value is [implicit](https://d3js.org/d3-scale/ordinal#scaleImplicit) (the default), then the _value_ is implicitly added to the domain and the next-available value in the range is assigned to _value_, such that this and subsequent invocations of the scale given the same input _value_ return the same output value.

## _ordinal_.domain( _domain_) [​](https://d3js.org/d3-scale/ordinal\#ordinal_domain)

[Examples](https://observablehq.com/@d3/d3-scaleordinal) · [Source](https://github.com/d3/d3-scale/blob/main/src/ordinal.js) · If _domain_ is specified, sets the domain to the specified array of values.

js

```
const color = d3.scaleOrdinal(["red", "green", "blue"]).domain(["a", "b", "c"]);
color("a"); // "red"
color("b"); // "green"
color("c"); // "blue"
```

The first element in _domain_ will be mapped to the first element in the range, the second domain value to the second range value, and so on. Domain values are stored internally in an [InternMap](https://d3js.org/d3-array/intern) from primitive value to index; the resulting index is then used to retrieve a value from the range. Thus, an ordinal scale’s values must be coercible to a primitive value, and the primitive domain value uniquely identifies the corresponding range value.

js

```
color.domain() // ["a", "b", "c"]
```

If _domain_ is not specified, this method returns the current domain.

Setting the domain on an ordinal scale is optional if the [unknown value](https://d3js.org/d3-scale/ordinal#ordinal_unknown) is [implicit](https://d3js.org/d3-scale/ordinal#scaleImplicit) (the default). In this case, the domain will be inferred implicitly from usage by assigning each unique value passed to the scale a new value from the range.

js

```
const color = d3.scaleOrdinal(["red", "green", "blue"]);
color("b"); // "red"
color("a"); // "green"
color("c"); // "blue"
color.domain(); // inferred ["b", "a", "c"]
```

CAUTION

An explicit domain is recommended for deterministic behavior; inferring the domain from usage is dependent on ordering.

## _ordinal_.range( _range_) [​](https://d3js.org/d3-scale/ordinal\#ordinal_range)

[Examples](https://observablehq.com/@d3/d3-scaleordinal) · [Source](https://github.com/d3/d3-scale/blob/main/src/ordinal.js) · If _range_ is specified, sets the range of the ordinal scale to the specified array of values.

js

```
const color = d3.scaleOrdinal().range(["red", "green", "blue"]);
```

The first element in the domain will be mapped to the first element in _range_, the second domain value to the second range value, and so on. If there are fewer elements in the range than in the domain, the scale will reuse values from the start of the range. If _range_ is not specified, this method returns the current range.

## _ordinal_.unknown( _value_) [​](https://d3js.org/d3-scale/ordinal\#ordinal_unknown)

[Examples](https://observablehq.com/@d3/d3-scaleordinal) · [Source](https://github.com/d3/d3-scale/blob/main/src/ordinal.js) · If _value_ is specified, sets the output value of the scale for unknown input values and returns this scale.

js

```
const color = d3.scaleOrdinal(["a", "b", "c"], d3.schemeTableau10).unknown(null);
color("a"); // "#4e79a7"
color("b"); // "#f28e2c"
color("c"); // "#e15759"
color("d"); // null
```

If _value_ is not specified, returns the current unknown value, which defaults to [implicit](https://d3js.org/d3-scale/ordinal#scaleImplicit). The implicit value enables implicit domain construction; see [_ordinal_.domain](https://d3js.org/d3-scale/ordinal#ordinal_domain).

## _ordinal_.copy() [​](https://d3js.org/d3-scale/ordinal\#ordinal_copy)

[Examples](https://observablehq.com/@d3/d3-scaleordinal) · [Source](https://github.com/d3/d3-scale/blob/main/src/ordinal.js) · Returns an exact copy of this ordinal scale.

js

```
const c1 = d3.scaleOrdinal(["a", "b", "c"], d3.schemeTableau10);
const c2 = c1.copy();
```

Changes to this scale will not affect the returned scale, and vice versa.

## scaleImplicit [​](https://d3js.org/d3-scale/ordinal\#scaleImplicit)

[Examples](https://observablehq.com/@d3/d3-scaleordinal) · [Source](https://github.com/d3/d3-scale/blob/main/src/ordinal.js) · A special value for [_ordinal_.unknown](https://d3js.org/d3-scale/ordinal#ordinal_unknown) that enables implicit domain construction: unknown values are implicitly added to the domain.

js

```
const color = d3.scaleOrdinal(["a", "b", "c"], d3.schemeTableau10);
color.unknown(); // d3.scaleImplicit
```

CAUTION

An explicit domain is recommended for deterministic behavior; inferring the domain from usage is dependent on ordering.

## Cylindrical Map Projections
[Skip to content](https://d3js.org/d3-geo/cylindrical#VPContent)

On this page

# Cylindrical projections [​](https://d3js.org/d3-geo/cylindrical\#cylindrical-projections)

Cylindrical projections project the sphere onto a containing cylinder, and then unroll the cylinder onto the plane. [Pseudocylindrical projections](https://web.archive.org/web/20150928042327/http://www.progonos.com/furuti/MapProj/Normal/ProjPCyl/projPCyl.html) are a generalization of cylindrical projections.

## geoEquirectangular() [​](https://d3js.org/d3-geo/cylindrical\#geoEquirectangular)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/equirectangular.js) · The equirectangular (plate carrée) projection.

## geoMercator() [​](https://d3js.org/d3-geo/cylindrical\#geoMercator)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/mercator.js) · The spherical Mercator projection. Defines a default [_projection_.clipExtent](https://d3js.org/d3-geo/projection#projection_clipExtent) such that the world is projected to a square, clipped to approximately ±85° latitude.

## geoTransverseMercator() [​](https://d3js.org/d3-geo/cylindrical\#geoTransverseMercator)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/transverseMercator.js) · The transverse spherical Mercator projection. Defines a default [_projection_.clipExtent](https://d3js.org/d3-geo/projection#projection_clipExtent) such that the world is projected to a square, clipped to approximately ±85° latitude.

## geoEqualEarth() [​](https://d3js.org/d3-geo/cylindrical\#geoEqualEarth)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/equalEarth.js) · The Equal Earth projection, an equal-area projection, by Bojan Šavrič _et al._, 2018.

## geoNaturalEarth1() [​](https://d3js.org/d3-geo/cylindrical\#geoNaturalEarth1)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/naturalEarth1.js) · The [Natural Earth projection](http://www.shadedrelief.com/NE_proj/) is a pseudocylindrical projection designed by Tom Patterson. It is neither conformal nor equal-area, but appealing to the eye for small-scale maps of the whole world.

## D3.js Position Forces
[Skip to content](https://d3js.org/d3-force/position#VPContent)

On this page

# Position forces [​](https://d3js.org/d3-force/position\#position-forces)

The [_x_](https://d3js.org/d3-force/position#forceX)\- and [_y_](https://d3js.org/d3-force/position#forceY)-position forces push nodes towards a desired position along the given dimension with a configurable strength. The [_radial_](https://d3js.org/d3-force/position#forceRadial) force is similar, except it pushes nodes towards the closest point on a given circle. The strength of the force is proportional to the one-dimensional distance between the node’s position and the target position. While these forces can be used to position individual nodes, they are intended primarily for global forces that apply to all (or most) nodes.

## forceX( _x_) [​](https://d3js.org/d3-force/position\#forceX)

[Source](https://github.com/d3/d3-force/blob/main/src/x.js) · Creates a new position force along the _x_-axis towards the given position [_x_](https://d3js.org/d3-force/position#x_x). If _x_ is not specified, it defaults to 0.

js

```
const x = d3.forceX(width / 2);
```

## _x_.strength( _strength_) [​](https://d3js.org/d3-force/position\#x_strength)

[Source](https://github.com/d3/d3-force/blob/main/src/x.js) · If _strength_ is specified, sets the strength accessor to the specified number or function, re-evaluates the strength accessor for each node, and returns this force. The _strength_ determines how much to increment the node’s _x_-velocity: ( [_x_](https://d3js.org/d3-force/position#x_x) \- _node_.x) × _strength_. For example, a value of 0.1 indicates that the node should move a tenth of the way from its current _x_-position to the target _x_-position with each application. Higher values moves nodes more quickly to the target position, often at the expense of other forces or constraints. A value outside the range \[0,1\] is not recommended.

If _strength_ is not specified, returns the current strength accessor, which defaults to:

js

```
function strength() {
  return 0.1;
}
```

The strength accessor is invoked for each [node](https://d3js.org/d3-force/simulation#simulation_nodes) in the simulation, being passed the _node_ and its zero-based _index_. The resulting number is then stored internally, such that the strength of each node is only recomputed when the force is initialized or when this method is called with a new _strength_, and not on every application of the force.

## _x_.x( _x_) [​](https://d3js.org/d3-force/position\#x_x)

[Source](https://github.com/d3/d3-force/blob/main/src/x.js) · If _x_ is specified, sets the _x_-coordinate accessor to the specified number or function, re-evaluates the _x_-accessor for each node, and returns this force. If _x_ is not specified, returns the current _x_-accessor, which defaults to:

js

```
function x() {
  return 0;
}
```

The _x_-accessor is invoked for each [node](https://d3js.org/d3-force/simulation#simulation_nodes) in the simulation, being passed the _node_ and its zero-based _index_. The resulting number is then stored internally, such that the target _x_-coordinate of each node is only recomputed when the force is initialized or when this method is called with a new _x_, and not on every application of the force.

## forceY( _y_) [​](https://d3js.org/d3-force/position\#forceY)

[Source](https://github.com/d3/d3-force/blob/main/src/y.js) · Creates a new position force along the _y_-axis towards the given position [_y_](https://d3js.org/d3-force/position#y_y). If _y_ is not specified, it defaults to 0.

js

```
const y = d3.forceY(height / 2);
```

## _y_.strength( _strength_) [​](https://d3js.org/d3-force/position\#y_strength)

[Source](https://github.com/d3/d3-force/blob/main/src/y.js) · If _strength_ is specified, sets the strength accessor to the specified number or function, re-evaluates the strength accessor for each node, and returns this force. The _strength_ determines how much to increment the node’s _y_-velocity: ( [_y_](https://d3js.org/d3-force/position#y_y) \- _node_.y) × _strength_. For example, a value of 0.1 indicates that the node should move a tenth of the way from its current _y_-position to the target _y_-position with each application. Higher values moves nodes more quickly to the target position, often at the expense of other forces or constraints. A value outside the range \[0,1\] is not recommended.

If _strength_ is not specified, returns the current strength accessor, which defaults to:

js

```
function strength() {
  return 0.1;
}
```

The strength accessor is invoked for each [node](https://d3js.org/d3-force/simulation#simulation_nodes) in the simulation, being passed the _node_ and its zero-based _index_. The resulting number is then stored internally, such that the strength of each node is only recomputed when the force is initialized or when this method is called with a new _strength_, and not on every application of the force.

## _y_.y( _y_) [​](https://d3js.org/d3-force/position\#y_y)

[Source](https://github.com/d3/d3-force/blob/main/src/y.js) · If _y_ is specified, sets the _y_-coordinate accessor to the specified number or function, re-evaluates the _y_-accessor for each node, and returns this force. If _y_ is not specified, returns the current _y_-accessor, which defaults to:

js

```
function y() {
  return 0;
}
```

The _y_-accessor is invoked for each [node](https://d3js.org/d3-force/simulation#simulation_nodes) in the simulation, being passed the _node_ and its zero-based _index_. The resulting number is then stored internally, such that the target y coordinate of each node is only recomputed when the force is initialized or when this method is called with a new _y_, and not on every application of the force.

## forceRadial( _radius_, _x_, _y_) [​](https://d3js.org/d3-force/position\#forceRadial)

[Source](https://github.com/d3/d3-force/blob/main/src/radial.js) · Creates a new position force towards a circle of the specified [_radius_](https://d3js.org/d3-force/position#radial_radius) centered at ⟨ [_x_](https://d3js.org/d3-force/position#radial_x), [_y_](https://d3js.org/d3-force/position#radial_y)⟩. If _x_ and _y_ are not specified, they default to ⟨0,0⟩.

js

```
const radial = d3.forceRadial(r, width / 2, height / 2);
```

## _radial_.strength( _strength_) [​](https://d3js.org/d3-force/position\#radial_strength)

[Source](https://github.com/d3/d3-force/blob/main/src/radial.js) · If _strength_ is specified, sets the strength accessor to the specified number or function, re-evaluates the strength accessor for each node, and returns this force. The _strength_ determines how much to increment the node’s _x_\- and _y_-velocity. For example, a value of 0.1 indicates that the node should move a tenth of the way from its current position to the closest point on the circle with each application. Higher values moves nodes more quickly to the target position, often at the expense of other forces or constraints. A value outside the range \[0,1\] is not recommended.

If _strength_ is not specified, returns the current strength accessor, which defaults to:

js

```
function strength() {
  return 0.1;
}
```

The strength accessor is invoked for each [node](https://d3js.org/d3-force/simulation#simulation_nodes) in the simulation, being passed the _node_ and its zero-based _index_. The resulting number is then stored internally, such that the strength of each node is only recomputed when the force is initialized or when this method is called with a new _strength_, and not on every application of the force.

## _radial_.radius( _radius_) [​](https://d3js.org/d3-force/position\#radial_radius)

[Source](https://github.com/d3/d3-force/blob/main/src/radial.js) · If _radius_ is specified, sets the circle _radius_ to the specified number or function, re-evaluates the _radius_ accessor for each node, and returns this force. If _radius_ is not specified, returns the current _radius_ accessor.

The _radius_ accessor is invoked for each [node](https://d3js.org/d3-force/simulation#simulation_nodes) in the simulation, being passed the _node_ and its zero-based _index_. The resulting number is then stored internally, such that the target radius of each node is only recomputed when the force is initialized or when this method is called with a new _radius_, and not on every application of the force.

## _radial_.x( _x_) [​](https://d3js.org/d3-force/position\#radial_x)

[Source](https://github.com/d3/d3-force/blob/main/src/radial.js) · If _x_ is specified, sets the _x_-coordinate of the circle center to the specified number and returns this force. If _x_ is not specified, returns the current _x_-coordinate of the center, which defaults to zero.

## _radial_.y( _y_) [​](https://d3js.org/d3-force/position\#radial_y)

[Source](https://github.com/d3/d3-force/blob/main/src/radial.js) · If _y_ is specified, sets the y coordinate of the circle center to the specified number and returns this force. If _y_ is not specified, returns the current y coordinate of the center, which defaults to zero.

## D3 Array Ticks
[Skip to content](https://d3js.org/d3-array/ticks#VPContent)

On this page

# Ticks [​](https://d3js.org/d3-array/ticks\#Ticks)

Generate representative values from a continuous interval.

## ticks( _start_, _stop_, _count_) [​](https://d3js.org/d3-array/ticks\#ticks)

[Examples](https://observablehq.com/@d3/d3-ticks) · [Source](https://github.com/d3/d3-array/blob/main/src/ticks.js) · Returns an array of approximately _count_ \+ 1 uniformly-spaced, nicely-rounded values between _start_ and _stop_ (inclusive). Each value is a power of ten multiplied by 1, 2 or 5.

js

```
d3.ticks(1, 9, 5) // [2, 4, 6, 8]
```

js

```
d3.ticks(1, 9, 20) // [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9]
```

Ticks are inclusive in the sense that they may include the specified _start_ and _stop_ values if (and only if) they are exact, nicely-rounded values consistent with the inferred [step](https://d3js.org/d3-array/ticks#tickStep). More formally, each returned tick _t_ satisfies _start_ ≤ _t_ and _t_ ≤ _stop_.

## tickIncrement( _start_, _stop_, _count_) [​](https://d3js.org/d3-array/ticks\#tickIncrement)

[Source](https://github.com/d3/d3-array/blob/main/src/ticks.js) · Like [d3.tickStep](https://d3js.org/d3-array/ticks#tickStep), except requires that _start_ is always less than or equal to _stop_, and if the tick step for the given _start_, _stop_ and _count_ would be less than one, returns the negative inverse tick step instead.

js

```
d3.tickIncrement(1, 9, 5) // 2
```

js

```
d3.tickIncrement(1, 9, 20) // -2, meaning a tick step 0.5
```

This method is always guaranteed to return an integer, and is used by [d3.ticks](https://d3js.org/d3-array/ticks#ticks) to guarantee that the returned tick values are represented as precisely as possible in IEEE 754 floating point.

## tickStep( _start_, _stop_, _count_) [​](https://d3js.org/d3-array/ticks\#tickStep)

[Source](https://github.com/d3/d3-array/blob/main/src/ticks.js) · Returns the difference between adjacent tick values if the same arguments were passed to [d3.ticks](https://d3js.org/d3-array/ticks#ticks): a nicely-rounded value that is a power of ten multiplied by 1, 2 or 5.

js

```
d3.tickStep(1, 9, 5) // 2
```

If _stop_ is less than _start_, may return a negative tick step to indicate descending ticks.

js

```
d3.tickStep(9, 1, 5) // -2
```

Note that due to the limited precision of IEEE 754 floating point, the returned value may not be exact decimals; use [d3-format](https://d3js.org/d3-format) to format numbers for human consumption.

## nice( _start_, _stop_, _count_) [​](https://d3js.org/d3-array/ticks\#nice)

[Source](https://github.com/d3/d3-array/blob/main/src/nice.js) · Returns a new interval \[ _niceStart_, _niceStop_\] covering the given interval \[ _start_, _stop_\] and where _niceStart_ and _niceStop_ are guaranteed to align with the corresponding [tick step](https://d3js.org/d3-array/ticks#tickStep).

js

```
d3.nice(1, 9, 5) // [0, 10]
```

Like [d3.tickIncrement](https://d3js.org/d3-array/ticks#tickIncrement), this requires that _start_ is less than or equal to _stop_.

## range( _start_, _stop_, _step_) [​](https://d3js.org/d3-array/ticks\#range)

[Examples](https://observablehq.com/@d3/d3-range) · [Source](https://github.com/d3/d3-array/blob/main/src/range.js) · Returns an array containing an arithmetic progression, similar to the Python built-in [range](http://docs.python.org/library/functions.html#range). This method is often used to iterate over a sequence of uniformly-spaced numeric values, such as the indexes of an array or the ticks of a linear scale. (See also [d3.ticks](https://d3js.org/d3-array/ticks#ticks) for nicely-rounded values.)

js

```
d3.range(6) // [0, 1, 2, 3, 4, 5]
```

If _step_ is omitted, it defaults to 1. If _start_ is omitted, it defaults to 0. The _stop_ value is exclusive; it is not included in the result. If _step_ is positive, the last element is the largest _start_ \+ _i_ \\* _step_ less than _stop_; if _step_ is negative, the last element is the smallest _start_ \+ _i_ \\* _step_ greater than _stop_.

js

```
d3.range(5, -1, -1) // [5, 4, 3, 2, 1, 0]
```

If the returned array would contain an infinite number of values, an empty range is returned.

js

```
d3.range(Infinity) // []
```

The arguments are not required to be integers; however, the results are more predictable if they are. The values in the returned array are defined as _start_ \+ _i_ \\* _step_, where _i_ is an integer from zero to one minus the total number of elements in the returned array.

js

```
d3.range(0, 1, 0.2) // [0, 0.2, 0.4, 0.6000000000000001, 0.8]
```

This behavior is due to IEEE 754 double-precision floating point, which defines 0.2 \* 3 = 0.6000000000000001. Use [d3-format](https://d3js.org/d3-format) to format numbers for human consumption with appropriate rounding; see also [_linear_.tickFormat](https://d3js.org/d3-scale/linear#linear_tickFormat) in [d3-scale](https://d3js.org/d3-scale). Likewise, if the returned array should have a specific length, consider using [_array_.map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map) on an integer range.

js

```
d3.range(0, 1, 1 / 49) // 👎 returns 50 elements!
```

js

```
d3.range(49).map((d) => d / 49) // 👍 returns 49 elements
```

## Logarithmic Scales in D3.js
[Skip to content](https://d3js.org/d3-scale/log#VPContent)

On this page

# Logarithmic scales [​](https://d3js.org/d3-scale/log\#logarithmic-scales)

Logarithmic (“log”) scales are like [linear scales](https://d3js.org/d3-scale/linear) except that a logarithmic transform is applied to the input domain value before the output range value is computed. The mapping to the range value _y_ can be expressed as a function of the domain value _x_: _y_ = _m_ log( _x_) \+ _b_.

CAUTION

As log(0) = -∞, a log scale domain must be **strictly-positive or strictly-negative**; the domain must not include or cross zero. A log scale with a positive domain has a well-defined behavior for positive values, and a log scale with a negative domain has a well-defined behavior for negative values. (For a negative domain, input and output values are implicitly multiplied by -1.) The behavior of the scale is undefined if you pass a negative value to a log scale with a positive domain or vice versa.

## scaleLog( _domain_, _range_) [​](https://d3js.org/d3-scale/log\#scaleLog)

[Examples](https://observablehq.com/@d3/continuous-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/log.js) · Constructs a new log scale with the specified [domain](https://d3js.org/d3-scale/linear#linear_domain) and [range](https://d3js.org/d3-scale/linear#linear_range), the [base](https://d3js.org/d3-scale/log#log_base) 10, the [default](https://d3js.org/d3-interpolate/value#interpolate) [interpolator](https://d3js.org/d3-scale/linear#linear_interpolate) and [clamping](https://d3js.org/d3-scale/linear#linear_clamp) disabled.

js

```
const x = d3.scaleLog([1, 10], [0, 960]);
```

If _domain_ is not specified, it defaults to \[1, 10\]. If _range_ is not specified, it defaults to \[0, 1\].

## _log_.base( _base_) [​](https://d3js.org/d3-scale/log\#log_base)

[Examples](https://observablehq.com/@d3/continuous-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/log.js) · If _base_ is specified, sets the base for this logarithmic scale to the specified value.

js

```
const x = d3.scaleLog([1, 1024], [0, 960]).base(2);
```

If _base_ is not specified, returns the current base, which defaults to 10. Note that due to the nature of a logarithmic transform, the base does not affect the encoding of the scale; it only affects which [ticks](https://d3js.org/d3-scale/log#log_ticks) are chosen.

## _log_.ticks( _count_) [​](https://d3js.org/d3-scale/log\#log_ticks)

[Examples](https://observablehq.com/@d3/scale-ticks) · [Source](https://github.com/d3/d3-scale/blob/main/src/log.js) · Like [_linear_.ticks](https://d3js.org/d3-scale/linear#linear_ticks), but customized for a log scale.

js

```
const x = d3.scaleLog([1, 100], [0, 960]);
const T = x.ticks(); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
```

If the [base](https://d3js.org/d3-scale/log#log_base) is an integer, the returned ticks are uniformly spaced within each integer power of base; otherwise, one tick per power of base is returned. The returned ticks are guaranteed to be within the extent of the domain. If the orders of magnitude in the [domain](https://d3js.org/d3-scale/linear#linear_domain) is greater than _count_, then at most one tick per power is returned. Otherwise, the tick values are unfiltered, but note that you can use [_log_.tickFormat](https://d3js.org/d3-scale/linear#linear_tickFormat) to filter the display of tick labels. If _count_ is not specified, it defaults to 10.

## _log_.tickFormat( _count_, _specifier_) [​](https://d3js.org/d3-scale/log\#log_tickFormat)

[Examples](https://observablehq.com/@d3/scale-ticks) · [Source](https://github.com/d3/d3-scale/blob/main/src/log.js) · Like [_linear_.tickFormat](https://d3js.org/d3-scale/linear#linear_tickFormat), but customized for a log scale. The specified _count_ typically has the same value as the count that is used to generate the [tick values](https://d3js.org/d3-scale/log#log_ticks).

js

```
const x = d3.scaleLog([1, 100], [0, 960]);
const T = x.ticks(); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, …]
const f = x.tickFormat();
T.map(f); // ["1", "2", "3", "4", "5", "", "", "", "", "10", …]
```

If there are too many ticks, the formatter may return the empty string for some of the tick labels; however, note that the ticks are still shown to convey the logarithmic transform accurately. To disable filtering, specify a _count_ of Infinity.

When specifying a count, you may also provide a format _specifier_ or format function. For example, to get a tick formatter that will display 20 ticks of a currency, say `log.tickFormat(20, "$,f")`. If the specifier does not have a defined precision, the precision will be set automatically by the scale, returning the appropriate format. This provides a convenient way of specifying a format whose precision will be automatically set by the scale.

## _log_.nice() [​](https://d3js.org/d3-scale/log\#log_nice)

[Examples](https://observablehq.com/@d3/continuous-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/log.js) · Like [_linear_.nice](https://d3js.org/d3-scale/linear#linear_nice), except extends the domain to integer powers of [base](https://d3js.org/d3-scale/log#log_base).

js

```
const x = d3.scaleLog([0.201479, 0.996679], [0, 960]).nice();
x.domain(); // [0.1, 1]
```

If the domain has more than two values, nicing the domain only affects the first and last value. Nicing a scale only modifies the current domain; it does not automatically nice domains that are subsequently set using [_log_.domain](https://d3js.org/d3-scale/linear#linear_domain). You must re-nice the scale after setting the new domain, if desired.

## D3.js Array Sorting
[Skip to content](https://d3js.org/d3-array/sort#VPContent)

On this page

# Sorting data [​](https://d3js.org/d3-array/sort\#sorting-data)

Sort values; see also [bisect](https://d3js.org/d3-array/bisect).

## ascending( _a_, _b_) [​](https://d3js.org/d3-array/sort\#ascending)

[Examples](https://observablehq.com/@d3/d3-ascending) · [Source](https://github.com/d3/d3-array/blob/main/src/ascending.js) · Returns -1 if _a_ is less than _b_, 1 if _a_ is greater than _b_, 0 if _a_ and _b_ are equivalent, and otherwise NaN.

js

```
[39, 21, 1, 104, 22].sort(d3.ascending) // [1, 21, 22, 39, 104]
```

This is the comparator function for natural order, and can be used with [_array_.sort](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) to arrange elements in ascending order.

## descending( _a_, _b_) [​](https://d3js.org/d3-array/sort\#descending)

[Examples](https://observablehq.com/@d3/d3-ascending) · [Source](https://github.com/d3/d3-array/blob/main/src/descending.js) · Returns -1 if _a_ is greater than _b_, 1 if _a_ is less than _b_, 0 if _a_ and _b_ are equivalent, and otherwise NaN.

js

```
[39, 21, 1, 104, 22].sort(d3.descending) // [104, 39, 22, 21, 1]
```

This is the comparator function for natural order, and can be used with [_array_.sort](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) to arrange elements in descending order.

## permute( _source_, _keys_) [​](https://d3js.org/d3-array/sort\#permute)

[Examples](https://observablehq.com/@d3/d3-permute) · [Source](https://github.com/d3/d3-array/blob/main/src/permute.js) · Returns a permutation of the specified _source_ array or object using the specified iterable of _keys_. The returned array contains the corresponding property of the source object for each key in _keys_, in order.

js

```
d3.permute(["a", "b", "c"], [1, 2, 0]) // returns ["b", "c", "a"]
```

The given _source_ need not be an array; for example, given an object

js

```
const object = {yield: 27, variety: "Manchuria", year: 1931, site: "University Farm"};
```

three fields could be extract like so

js

```
d3.permute(object, ["site", "variety", "yield"]) // ["University Farm", "Manchuria", 27]
```

## quickselect( _array_, _k_, _lo_, _hi_, _compare_) [​](https://d3js.org/d3-array/sort\#quickselect)

[Examples](https://observablehq.com/@d3/d3-quickselect) · [Source](https://github.com/d3/d3-array/blob/main/src/quickselect.js) · Rearranges the elements of _array_ between _lo_ and _hi_ (inclusive) in-place such that _array_\[ _k_\] is the ( _k_ \- _lo_ \+ 1)-th smallest value and _array_.slice( _lo_, _k_) are the _k_ smallest elements, according to the given _compare_ function, and returns the given _array_. If _lo_ is not specified, it defaults to zero; if _hi_ is not specified, it defaults to _array_.length - 1; if _compare_ is not specified, it defaults to [ascending](https://d3js.org/d3-array/sort#ascending).

For example, given an array of numbers:

js

```
const numbers = [65, 28, 59, 33, 21, 56, 22, 95, 50, 12, 90, 53, 28, 77, 39];
```

To select the smallest 8 elements:

js

```
d3.quickselect(numbers, 8)
```

The rearranged _numbers_ is

js

```
[39, 28, 28, 33, 21, 12, 22, 50, 53, 56, 59, 65, 90, 77, 95]
//                               ^^ numbers[k]
```

where _numbers_\[8\] is 53: greater than the preceding _k_ elements and less than the following elements. Implemented by [Volodymyr Agafonkin’s quickselect](https://github.com/mourner/quickselect).

## reverse( _iterable_) [​](https://d3js.org/d3-array/sort\#reverse)

[Source](https://github.com/d3/d3-array/blob/main/src/reverse.js) · Returns an array containing the values in the given _iterable_ in reverse order.

js

```
d3.reverse(new Set([0, 2, 3, 1])) // [1, 3, 2, 0]
```

Equivalent to [_array_.reverse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse), except that it does not mutate the given input and works with any iterable.

## shuffle( _array_, _start_, _stop_) [​](https://d3js.org/d3-array/sort\#shuffle)

[Examples](https://observablehq.com/@d3/d3-shuffle) · [Source](https://github.com/d3/d3-array/blob/main/src/shuffle.js) · Randomizes the order of the specified _array_ in-place using the [Fisher–Yates shuffle](https://bost.ocks.org/mike/shuffle/) and returns the _array_.

js

```
d3.shuffle([..."abcdefg"]) // ["e", "c", "a", "d", "b", "g", "f"], perhaps
```

If _start_ is specified, it is the starting index (inclusive) of the _array_ to shuffle; if _start_ is not specified, it defaults to zero. If _stop_ is specified, it is the ending index (exclusive) of the _array_ to shuffle; if _stop_ is not specified, it defaults to _array_.length. For example, to shuffle the first ten elements of the _array_: shuffle( _array_, 0, 10).

## shuffler( _random_) [​](https://d3js.org/d3-array/sort\#shuffler)

[Source](https://github.com/d3/d3-array/blob/main/src/shuffle.js) · Returns a [shuffle function](https://d3js.org/d3-array/sort#shuffle) given the specified random source.

js

```
d3.shuffler(d3.randomLcg(42))([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) // [5, 3, 7, 6, 8, 9, 1, 4, 0, 2]
```

Often used with [d3.randomLcg](https://d3js.org/d3-random) for a deterministic shuffle.

## sort( _iterable_, _comparator_) [​](https://d3js.org/d3-array/sort\#sort)

[Source](https://github.com/d3/d3-array/blob/main/src/sort.js) · Returns an array containing the values in the given _iterable_ in the sorted order defined by the given _comparator_ or _accessor_ function. If _comparator_ is not specified, it defaults to [d3.ascending](https://d3js.org/d3-array/sort#ascending).

js

```
d3.sort(new Set([0, 2, 3, 1])) // [0, 1, 2, 3]
```

If an _accessor_ (a function that does not take exactly two arguments) is specified,

js

```
d3.sort(data, (d) => d.value)
```

it is equivalent to a _comparator_ using [natural order](https://d3js.org/d3-array/sort#ascending):

js

```
d3.sort(data, (a, b) => d3.ascending(a.value, b.value))
```

The _accessor_ is only invoked once per element, and thus the returned sorted order is consistent even if the accessor is nondeterministic. Multiple accessors may be specified to break ties.

js

```
d3.sort(points, ({x}) => x, ({y}) => y)
```

The above is equivalent to:

js

```
d3.sort(data, (a, b) => d3.ascending(a.x, b.x) || d3.ascending(a.y, b.y))
```

Unlike [_array_.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), d3.sort does not mutate the given input, the comparator defaults to natural order instead of lexicographic order, and the input can be any iterable.

## D3.js Cluster Layout
[Skip to content](https://d3js.org/d3-hierarchy/cluster#VPContent)

On this page

# Cluster [​](https://d3js.org/d3-hierarchy/cluster\#Cluster)

/Chaos/Chaos/Eros/Chaos/Erebus/Chaos/Tartarus/Chaos/Gaia/Chaos/Gaia/Mountains/Chaos/Gaia/Pontus/Chaos/Gaia/UranusEros/Chaos/ErosErebus/Chaos/ErebusTartarus/Chaos/TartarusMountains/Chaos/Gaia/MountainsPontus/Chaos/Gaia/PontusUranus/Chaos/Gaia/UranusChaos/ChaosGaia/Chaos/Gaia

[Examples](https://observablehq.com/@d3/cluster-dendrogram) · The cluster layout produces [dendrograms](http://en.wikipedia.org/wiki/Dendrogram): node-link diagrams that place leaf nodes of the tree at the same depth. Dendrograms are typically less compact than [tidy trees](https://d3js.org/d3-hierarchy/tree), but are useful when all the leaves should be at the same level, such as for hierarchical clustering or [phylogenetic tree diagrams](https://observablehq.com/@d3/tree-of-life).

## cluster() [​](https://d3js.org/d3-hierarchy/cluster\#cluster)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/cluster.js) · Creates a new cluster layout with default settings.

## _cluster_( _root_) [​](https://d3js.org/d3-hierarchy/cluster\#_cluster)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/cluster.js) · Lays out the specified _root_ [hierarchy](https://d3js.org/d3-hierarchy/hierarchy), assigning the following properties on _root_ and its descendants:

- _node_.x - the _x_-coordinate of the node
- _node_.y - the y coordinate of the node

The coordinates _x_ and _y_ represent an arbitrary coordinate system; for example, you can treat _x_ as an angle and _y_ as a radius to produce a [radial layout](https://observablehq.com/@d3/radial-dendrogram). You may want to call [_root_.sort](https://d3js.org/d3-hierarchy/hierarchy#node_sort) before passing the hierarchy to the cluster layout.

## _cluster_.size( _size_) [​](https://d3js.org/d3-hierarchy/cluster\#cluster_size)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/cluster.js) · If _size_ is specified, sets this cluster layout’s size to the specified two-element array of numbers \[ _width_, _height_\] and returns this cluster layout. If _size_ is not specified, returns the current layout size, which defaults to \[1, 1\]. A layout size of null indicates that a [node size](https://d3js.org/d3-hierarchy/cluster#cluster_nodeSize) will be used instead. The coordinates _x_ and _y_ represent an arbitrary coordinate system; for example, to produce a [radial layout](https://observablehq.com/@d3/radial-dendrogram), a size of \[360, _radius_\] corresponds to a breadth of 360° and a depth of _radius_.

## _cluster_.nodeSize( _size_) [​](https://d3js.org/d3-hierarchy/cluster\#cluster_nodeSize)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/cluster.js) · If _size_ is specified, sets this cluster layout’s node size to the specified two-element array of numbers \[ _width_, _height_\] and returns this cluster layout. If _size_ is not specified, returns the current node size, which defaults to null. A node size of null indicates that a [layout size](https://d3js.org/d3-hierarchy/cluster#cluster_size) will be used instead. When a node size is specified, the root node is always positioned at ⟨0, 0⟩.

## _cluster_.separation( _separation_) [​](https://d3js.org/d3-hierarchy/cluster\#cluster_separation)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/cluster.js) · If _separation_ is specified, sets the separation accessor to the specified function and returns this cluster layout. If _separation_ is not specified, returns the current separation accessor, which defaults to:

js

```
function separation(a, b) {
  return a.parent == b.parent ? 1 : 2;
}
```

The separation accessor is used to separate neighboring leaves. The separation function is passed two leaves _a_ and _b_, and must return the desired separation. The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent.

## Hierarchical Data Structures
[Skip to content](https://d3js.org/d3-hierarchy/hierarchy#VPContent)

On this page

# Hierarchies [​](https://d3js.org/d3-hierarchy/hierarchy\#hierarchies)

Before you can compute a [hierarchical layout](https://d3js.org/d3-hierarchy), you need a root node. If your data is already in a hierarchical format, such as JSON, you can pass it directly to [hierarchy](https://d3js.org/d3-hierarchy/hierarchy#hierarchy); otherwise, you can rearrange tabular data, such as comma-separated values (CSV), into a hierarchy using [stratify](https://d3js.org/d3-hierarchy/stratify).

## hierarchy( _data_, _children_) [​](https://d3js.org/d3-hierarchy/hierarchy\#hierarchy)

[Examples](https://observablehq.com/@d3/d3-hierarchy) · [Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/index.js) · Constructs a root node from the specified hierarchical _data_. The specified _data_ must be an object representing the root node. For example:

js

```
const data = {
  name: "Eve",
  children: [\
    {name: "Cain"},\
    {name: "Seth", children: [{name: "Enos"}, {name: "Noam"}]},\
    {name: "Abel"},\
    {name: "Awan", children: [{name: "Enoch"}]},\
    {name: "Azura"}\
  ]
};
```

To construct a hierarchy:

js

```
const root = d3.hierarchy(data);
```

The specified _children_ accessor function is invoked for each datum, starting with the root _data_, and must return an iterable of data representing the children, if any. If the children accessor is not specified, it defaults to:

js

```
function children(d) {
  return d.children;
}
```

If _data_ is a Map, it is implicitly converted to the entry \[undefined, _data_\], and the children accessor instead defaults to:

js

```
function children(d) {
  return Array.isArray(d) ? d[1] : null;
}
```

This allows you to pass the result of [group](https://d3js.org/d3-array/group#group) or [rollup](https://d3js.org/d3-array/group#rollup) to hierarchy.

The returned root node and each descendant has the following properties:

- _node_.data - the associated data as passed to [hierarchy](https://d3js.org/d3-hierarchy/hierarchy#hierarchy)
- _node_.depth - zero for the root, increasing by one for each descendant generation
- _node_.height - the greatest distance from any descendant leaf, or zero for leaves
- _node_.parent - the parent node, or null for the root node
- _node_.children - an array of child nodes, if any, or undefined for leaves
- _node_.value - the optional summed value of the node and its [descendants](https://d3js.org/d3-hierarchy/hierarchy#node_descendants)

This method can also be used to test if a node is an `instanceof d3.hierarchy` and to extend the node prototype.

## _node_.ancestors() [​](https://d3js.org/d3-hierarchy/hierarchy\#node_ancestors)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/ancestors.js) · Returns the array of ancestors nodes, starting with this node, then followed by each parent up to the root.

## _node_.descendants() [​](https://d3js.org/d3-hierarchy/hierarchy\#node_descendants)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/descendants.js) · Returns the array of descendant nodes, starting with this node, then followed by each child in topological order.

## _node_.leaves() [​](https://d3js.org/d3-hierarchy/hierarchy\#node_leaves)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/leaves.js) · Returns the array of leaf nodes in traversal order. A _leaf_ is a node with no children.

## _node_.find( _filter_) [​](https://d3js.org/d3-hierarchy/hierarchy\#node_find)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/find.js) · Returns the first node in the hierarchy from this _node_ for which the specified _filter_ returns a truthy value. Returns undefined if no such node is found.

## _node_.path( _target_) [​](https://d3js.org/d3-hierarchy/hierarchy\#node_path)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/path.js) · Returns the shortest path through the hierarchy from this _node_ to the specified _target_ node. The path starts at this _node_, ascends to the least common ancestor of this _node_ and the _target_ node, and then descends to the _target_ node. This is useful for [hierarchical edge bundling](https://observablehq.com/@d3/hierarchical-edge-bundling).

## _node_.links() [​](https://d3js.org/d3-hierarchy/hierarchy\#node_links)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/links.js) · Returns an array of links for this _node_ and its descendants, where each _link_ is an object that defines source and target properties. The source of each link is the parent node, and the target is a child node.

## _node_.sum( _value_) [​](https://d3js.org/d3-hierarchy/hierarchy\#node_sum)

[Examples](https://observablehq.com/@d3/visiting-a-d3-hierarchy) · [Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/sum.js) · Evaluates the specified _value_ function for this _node_ and each descendant in [post-order traversal](https://d3js.org/d3-hierarchy/hierarchy#node_eachAfter), and returns this _node_. The _node_.value property of each node is set to the numeric value returned by the specified function plus the combined value of all children. The function is passed the node’s data, and must return a non-negative number. The _value_ accessor is evaluated for _node_ and every descendant, including internal nodes; if you only want leaf nodes to have internal value, then return zero for any node with children. [For example](https://observablehq.com/@d3/treemap-by-count), as an alternative to [_node_.count](https://d3js.org/d3-hierarchy/hierarchy#node_count):

js

```
root.sum((d) => d.value ? 1 : 0);
```

You must call _node_.sum or [_node_.count](https://d3js.org/d3-hierarchy/hierarchy#node_count) before invoking a hierarchical layout that requires _node_.value, such as [treemap](https://d3js.org/d3-hierarchy/treemap). For example:

js

```
// Construct the treemap layout.
const treemap = d3.treemap();
treemap.size([width, height]);
treemap.padding(2);

// Sum and sort the data.
root.sum((d) => d.value);
root.sort((a, b) => b.height - a.height || b.value - a.value);

// Compute the treemap layout.
treemap(root);

// Retrieve all descendant nodes.
const nodes = root.descendants();
```

Since the API supports [method chaining](https://en.wikipedia.org/wiki/Method_chaining), you can also say:

js

```
d3.treemap()
    .size([width, height])
    .padding(2)
  (root
      .sum((d) => d.value)
      .sort((a, b) => b.height - a.height || b.value - a.value))
  .descendants()
```

This example assumes that the node data has a value field.

## _node_.count() [​](https://d3js.org/d3-hierarchy/hierarchy\#node_count)

[Examples](https://observablehq.com/@d3/visiting-a-d3-hierarchy) · [Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/count.js) · Computes the number of leaves under this _node_ and assigns it to _node_.value, and similarly for every descendant of _node_. If this _node_ is a leaf, its count is one. Returns this _node_. See also [_node_.sum](https://d3js.org/d3-hierarchy/hierarchy#node_sum).

## _node_.sort(compare) [​](https://d3js.org/d3-hierarchy/hierarchy\#node_sort)

[Examples](https://observablehq.com/@d3/visiting-a-d3-hierarchy) · [Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/sort.js) · Sorts the children of this _node_, if any, and each of this _node_’s descendants’ children, in [pre-order traversal](https://d3js.org/d3-hierarchy/hierarchy#node_eachBefore) using the specified _compare_ function, and returns this _node_.

The specified function is passed two nodes _a_ and _b_ to compare. If _a_ should be before _b_, the function must return a value less than zero; if _b_ should be before _a_, the function must return a value greater than zero; otherwise, the relative order of _a_ and _b_ are not specified. See [_array_.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) for more.

Unlike [_node_.sum](https://d3js.org/d3-hierarchy/hierarchy#node_sum), the _compare_ function is passed two [nodes](https://d3js.org/d3-hierarchy/hierarchy#hierarchy) rather than two nodes’ data. For example, if the data has a value property, this sorts nodes by the descending aggregate value of the node and all its descendants, as is recommended for [circle-packing](https://d3js.org/d3-hierarchy/pack):

js

```
root
    .sum((d) => d.value)
    .sort((a, b) => b.value - a.value);
```

Similarly, to sort nodes by descending height (greatest distance from any descendant leaf) and then descending value, as is recommended for [treemaps](https://d3js.org/d3-hierarchy/treemap) and [icicles](https://d3js.org/d3-hierarchy/partition):

js

```
root
    .sum((d) => d.value)
    .sort((a, b) => b.height - a.height || b.value - a.value);
```

To sort nodes by descending height and then ascending id, as is recommended for [trees](https://d3js.org/d3-hierarchy/tree) and [dendrograms](https://d3js.org/d3-hierarchy/cluster):

js

```
root
    .sum((d) => d.value)
    .sort((a, b) => b.height - a.height || d3.ascending(a.id, b.id));
```

You must call _node_.sort before invoking a hierarchical layout if you want the new sort order to affect the layout; see [_node_.sum](https://d3js.org/d3-hierarchy/hierarchy#node_sum) for an example.

## node\[Symbol.iterator\]() [​](https://d3js.org/d3-hierarchy/hierarchy\#node_iterator)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/iterator.js) · Returns an iterator over the _node_’s descendants in breadth-first order. For example:

js

```
for (const descendant of node) {
  console.log(descendant);
}
```

## _node_.each( _function_, _that_) [​](https://d3js.org/d3-hierarchy/hierarchy\#node_each)

[Examples](https://observablehq.com/@d3/visiting-a-d3-hierarchy) · [Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/each.js) · Invokes the specified _function_ for _node_ and each descendant in [breadth-first order](https://en.wikipedia.org/wiki/Breadth-first_search), such that a given _node_ is only visited if all nodes of lesser depth have already been visited, as well as all preceding nodes of the same depth. The specified function is passed the current _descendant_, the zero-based traversal _index_, and this _node_. If _that_ is specified, it is the this context of the callback.

## _node_.eachAfter( _function_, _that_) [​](https://d3js.org/d3-hierarchy/hierarchy\#node_eachAfter)

[Examples](https://observablehq.com/@d3/visiting-a-d3-hierarchy) · [Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/eachAfter.js) · Invokes the specified _function_ for _node_ and each descendant in [post-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#Post-order), such that a given _node_ is only visited after all of its descendants have already been visited. The specified function is passed the current _descendant_, the zero-based traversal _index_, and this _node_. If _that_ is specified, it is the this context of the callback.

## _node_.eachBefore( _function_, _that_) [​](https://d3js.org/d3-hierarchy/hierarchy\#node_eachBefore)

[Examples](https://observablehq.com/@d3/visiting-a-d3-hierarchy) · [Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/eachBefore.js) · Invokes the specified _function_ for _node_ and each descendant in [pre-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order), such that a given _node_ is only visited after all of its ancestors have already been visited. The specified function is passed the current _descendant_, the zero-based traversal _index_, and this _node_. If _that_ is specified, it is the this context of the callback.

## _node_.copy() [​](https://d3js.org/d3-hierarchy/hierarchy\#node_copy)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/hierarchy/index.js) · Return a deep copy of the subtree starting at this _node_. (The returned deep copy shares the same data, however.) The returned node is the root of a new tree; the returned node’s parent is always null and its depth is always zero.

## D3 Array Methods
[Skip to content](https://d3js.org/d3-array#VPContent)

Return to top

# d3-array [​](https://d3js.org/d3-array\#d3-array)

Array manipulation, ordering, searching, summarizing, _etc._

See one of:

- [Adding numbers](https://d3js.org/d3-array/add) \- Add floating point values with full precision.
- [Binning data](https://d3js.org/d3-array/bin) \- Bin discrete samples into continuous, non-overlapping intervals.
- [Bisecting data](https://d3js.org/d3-array/bisect) \- Quickly find a value in a sorted array.
- [Blurring data](https://d3js.org/d3-array/blur) \- Blur quantitative values in one or two dimensions.
- [Grouping data](https://d3js.org/d3-array/group) \- Group discrete values.
- [Interning values](https://d3js.org/d3-array/intern) \- Create maps and sets with non-primitive values such as dates.
- [Set operations](https://d3js.org/d3-array/sets) \- Logical operations on sets.
- [Sorting data](https://d3js.org/d3-array/sort) \- Sort and reorder arrays of values.
- [Summarizing data](https://d3js.org/d3-array/summarize) \- Compute summary statistics.
- [Ticks](https://d3js.org/d3-array/ticks) \- Generate representative values from a continuous interval.
- [Transforming data](https://d3js.org/d3-array/transform) \- Derive new arrays.

## D3.js Full Precision Addition
[Skip to content](https://d3js.org/d3-array/add#VPContent)

On this page

# Adding numbers [​](https://d3js.org/d3-array/add\#adding-numbers)

Add floating point numbers with full precision.

## new Adder() [​](https://d3js.org/d3-array/add\#Adder)

js

```
const adder = new d3.Adder();
```

[Examples](https://observablehq.com/@d3/d3-fsum) · [Source](https://github.com/d3/d3-array/blob/main/src/fsum.js) · Creates a new adder with an initial value of 0.

## _adder_.add( _number_) [​](https://d3js.org/d3-array/add\#adder_add)

js

```
adder.add(42)
```

Adds the specified _number_ to the adder’s current value and returns the adder.

## _adder_.valueOf() [​](https://d3js.org/d3-array/add\#adder_valueOf)

js

```
adder.valueOf() // 42
```

Returns the IEEE 754 double-precision representation of the adder’s current value. Most useful as the short-hand notation `+adder`, or when coercing as `Number(adder)`.

## fsum( _values_, _accessor_) [​](https://d3js.org/d3-array/add\#fsum)

js

```
d3.fsum([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) // 1
```

[Examples](https://observablehq.com/@d3/d3-fsum) · [Source](https://github.com/d3/d3-array/blob/main/src/fsum.js) · Returns a full-precision summation of the given _values_. Although slower, d3.fsum can replace [d3.sum](https://d3js.org/d3-array/summarize#sum) wherever greater precision is needed.

js

```
d3.fsum(penguins, (d) => d.body_mass_g) // 1437000
```

If an _accessor_ is specified, invokes the given function for each element in the input _values_, being passed the element `d`, the index `i`, and the array `data` as three arguments; the returned values will then be added.

## fcumsum( _values_, _accessor_) [​](https://d3js.org/d3-array/add\#fcumsum)

js

```
d3.fcumsum([1, 1e-14, -1]) // [1, 1.00000000000001, 1e-14]
```

[Examples](https://observablehq.com/@d3/d3-fcumsum) · [Source](https://github.com/d3/d3-array/blob/main/src/fsum.js) · Returns a full-precision cumulative sum of the given _values_ as a Float64Array. Although slower, d3.fcumsum can replace [d3.cumsum](https://d3js.org/d3-array/summarize#cumsum) when greater precision is needed.

js

```
d3.fcumsum(penguins, (d) => d.body_mass_g) // [3750, 7550, 10800, 10800, 14250, …]
```

If an _accessor_ is specified, invokes the given function for each element in the input _values_, being passed the element `d`, the index `i`, and the array `data` as three arguments; the returned values will then be added.

## D3 Data Joining
[Skip to content](https://d3js.org/d3-selection/joining#VPContent)

On this page

# Joining data [​](https://d3js.org/d3-selection/joining\#joining-data)

For an introduction, see [Thinking With Joins](http://bost.ocks.org/mike/join/) and the [_selection_.join notebook](https://observablehq.com/@d3/selection-join).

## _selection_.data( _data_, _key_) [​](https://d3js.org/d3-selection/joining\#selection_data)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/data.js) · Binds the specified array of _data_ with the selected elements, returning a new selection that represents the _update_ selection: the elements successfully bound to data. Also defines the [enter](https://d3js.org/d3-selection/joining#selection_enter) and [exit](https://d3js.org/d3-selection/joining#selection_exit) selections on the returned selection, which can be used to add or remove elements to correspond to the new data. The specified _data_ is an array of arbitrary values ( _e.g._, numbers or objects), or a function that returns an array of values for each group. When data is assigned to an element, it is stored in the property `__data__`, thus making the data “sticky” and available on re-selection.

The _data_ is specified **for each group** in the selection. If the selection has multiple groups (such as [d3.selectAll](https://d3js.org/d3-selection/selecting#selectAll) followed by [_selection_.selectAll](https://d3js.org/d3-selection/selecting#selection_selectAll)), then _data_ should typically be specified as a function. This function will be evaluated for each group in order, being passed the group’s parent datum ( _d_, which may be undefined), the group index ( _i_), and the selection’s parent nodes ( _nodes_), with _this_ as the group’s parent element.

In conjunction with [_selection_.join](https://d3js.org/d3-selection/joining#selection_join) (or more explicitly with [_selection_.enter](https://d3js.org/d3-selection/joining#selection_enter), [_selection_.exit](https://d3js.org/d3-selection/joining#selection_exit), [_selection_.append](https://d3js.org/d3-selection/modifying#selection_append) and [_selection_.remove](https://d3js.org/d3-selection/modifying#selection_remove)), _selection_.data can be used to enter, update and exit elements to match data. For example, to create an HTML table from a matrix of numbers:

js

```
const matrix = [\
  [11975,  5871, 8916, 2868],\
  [ 1951, 10048, 2060, 6171],\
  [ 8010, 16145, 8090, 8045],\
  [ 1013,   990,  940, 6907]\
];

d3.select("body")
  .append("table")
  .selectAll("tr")
  .data(matrix)
  .join("tr")
  .selectAll("td")
  .data(d => d)
  .join("td")
    .text(d => d);
```

In this example the _data_ function is the identity function: for each table row, it returns the corresponding row from the data matrix.

If a _key_ function is not specified, then the first datum in _data_ is assigned to the first selected element, the second datum to the second selected element, and so on. A _key_ function may be specified to control which datum is assigned to which element, replacing the default join-by-index, by computing a string identifier for each datum and element. This key function is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]); the returned string is the element’s key. The key function is then also evaluated for each new datum in _data_, being passed the current datum ( _d_), the current index ( _i_), and the group’s new _data_, with _this_ as the group’s parent DOM element; the returned string is the datum’s key. The datum for a given key is assigned to the element with the matching key. If multiple elements have the same key, the duplicate elements are put into the exit selection; if multiple data have the same key, the duplicate data are put into the enter selection.

For example, given this document:

html

```
<div id="Ford"></div>
<div id="Jarrah"></div>
<div id="Kwon"></div>
<div id="Locke"></div>
<div id="Reyes"></div>
<div id="Shephard"></div>
```

You could join data by key as follows:

js

```
const data = [\
  {name: "Locke", number: 4},\
  {name: "Reyes", number: 8},\
  {name: "Ford", number: 15},\
  {name: "Jarrah", number: 16},\
  {name: "Shephard", number: 23},\
  {name: "Kwon", number: 42}\
];

d3.selectAll("div")
  .data(data, function(d) { return d ? d.name : this.id; })
    .text(d => d.number);
```

This example key function uses the datum _d_ if present, and otherwise falls back to the element’s id property. Since these elements were not previously bound to data, the datum _d_ is null when the key function is evaluated on selected elements, and non-null when the key function is evaluated on the new data.

The _update_ and _enter_ selections are returned in data order, while the _exit_ selection preserves the selection order prior to the join. If a key function is specified, the order of elements in the selection may not match their order in the document; use [_selection_.order](https://d3js.org/d3-selection/modifying#selection_order) or [_selection_.sort](https://d3js.org/d3-selection/modifying#selection_sort) as needed. For more on how the key function affects the join, see [A Bar Chart, Part 2](https://observablehq.com/@d3/lets-make-a-bar-chart/2) and [Object Constancy](http://bost.ocks.org/mike/constancy/).

If _data_ is not specified, this method returns the array of data for the selected elements.

This method cannot be used to clear bound data; use [_selection_.datum](https://d3js.org/d3-selection/joining#selection_datum) instead.

## _selection_.join( _enter_, _update_, _exit_) [​](https://d3js.org/d3-selection/joining\#selection_join)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/join.js) · Appends, removes and reorders elements as necessary to match the data that was previously bound by [_selection_.data](https://d3js.org/d3-selection/joining#selection_data), returning the [merged](https://d3js.org/d3-selection/joining#selection_merge) enter and update selection. This method is a convenient alternative to the explicit [general update pattern](https://observablehq.com/@d3/general-update-pattern), replacing [_selection_.enter](https://d3js.org/d3-selection/joining#selection_enter), [_selection_.exit](https://d3js.org/d3-selection/joining#selection_exit), [_selection_.append](https://d3js.org/d3-selection/modifying#selection_append), [_selection_.remove](https://d3js.org/d3-selection/modifying#selection_remove), and [_selection_.order](https://d3js.org/d3-selection/modifying#selection_order). For example:

js

```
svg.selectAll("circle")
  .data(data)
  .join("circle")
    .attr("fill", "none")
    .attr("stroke", "black");
```

The _enter_ function may be specified as a string shorthand, as above, which is equivalent to [_selection_.append](https://d3js.org/d3-selection/modifying#selection_append) with the given element name. Likewise, optional _update_ and _exit_ functions may be specified, which default to the identity function and calling [_selection_.remove](https://d3js.org/d3-selection/modifying#selection_remove), respectively. The shorthand above is thus equivalent to:

js

```
svg.selectAll("circle")
  .data(data)
  .join(
    enter => enter.append("circle"),
    update => update,
    exit => exit.remove()
  )
    .attr("fill", "none")
    .attr("stroke", "black");
```

By passing separate functions on enter, update and exit, you have greater control over what happens. And by specifying a key function to [_selection_.data](https://d3js.org/d3-selection/joining#selection_data), you can minimize changes to the DOM to optimize performance. For example, to set different fill colors for enter and update:

js

```
svg.selectAll("circle")
  .data(data)
  .join(
    enter => enter.append("circle").attr("fill", "green"),
    update => update.attr("fill", "blue")
  )
    .attr("stroke", "black");
```

The selections returned by the _enter_ and _update_ functions are merged and then returned by _selection_.join.

You can animate enter, update and exit by creating transitions inside the _enter_, _update_ and _exit_ functions. If the _enter_ and _update_ functions return transitions, their underlying selections are merged and then returned by _selection_.join. The return value of the _exit_ function is not used.

For more, see the [_selection_.join notebook](https://observablehq.com/@d3/selection-join).

## _selection_.enter() [​](https://d3js.org/d3-selection/joining\#selection_enter)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/enter.js) · Returns the enter selection: placeholder nodes for each datum that had no corresponding DOM element in the selection. (The enter selection is empty for selections not returned by [_selection_.data](https://d3js.org/d3-selection/joining#selection_data).)

The enter selection is typically used to create “missing” elements corresponding to new data. For example, to create DIV elements from an array of numbers:

js

```
const div = d3.select("body")
  .selectAll("div")
  .data([4, 8, 15, 16, 23, 42])
  .enter().append("div")
    .text(d => d);
```

If the body is initially empty, the above code will create six new DIV elements, append them to the body in-order, and assign their text content as the associated (string-coerced) number:

html

```
<div>4</div>
<div>8</div>
<div>15</div>
<div>16</div>
<div>23</div>
<div>42</div>
```

Conceptually, the enter selection’s placeholders are pointers to the parent element (in this example, the document body). The enter selection is typically only used transiently to append elements, and is often [merged](https://d3js.org/d3-selection/joining#selection_merge) with the update selection after appending, such that modifications can be applied to both entering and updating elements.

## _selection_.exit() [​](https://d3js.org/d3-selection/joining\#selection_exit)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/exit.js) · Returns the exit selection: existing DOM elements in the selection for which no new datum was found. (The exit selection is empty for selections not returned by [_selection_.data](https://d3js.org/d3-selection/joining#selection_data).)

The exit selection is typically used to remove “superfluous” elements corresponding to old data. For example, to update the DIV elements created previously with a new array of numbers:

js

```
div = div.data([1, 2, 4, 8, 16, 32], d => d);
```

Since a key function was specified (as the identity function), and the new data contains the numbers \[4, 8, 16\] which match existing elements in the document, the update selection contains three DIV elements. Leaving those elements as-is, we can append new elements for \[1, 2, 32\] using the enter selection:

js

```
div.enter().append("div").text(d => d);
```

Likewise, to remove the exiting elements \[15, 23, 42\]:

js

```
div.exit().remove();
```

Now the document body looks like this:

html

```
<div>1</div>
<div>2</div>
<div>4</div>
<div>8</div>
<div>16</div>
<div>32</div>
```

The order of the DOM elements matches the order of the data because the old data’s order and the new data’s order were consistent. If the new data’s order is different, use [_selection_.order](https://d3js.org/d3-selection/modifying#selection_order) to reorder the elements in the DOM. See the [general update pattern](https://observablehq.com/@d3/general-update-pattern) notebook for more on data joins.

## _selection_.datum(value) [​](https://d3js.org/d3-selection/joining\#selection_datum)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/datum.js) · Gets or sets the bound data for each selected element. Unlike [_selection_.data](https://d3js.org/d3-selection/joining#selection_data), this method does not compute a join and does not affect indexes or the enter and exit selections.

If a _value_ is specified, sets the element’s bound data to the specified value on all selected elements. If the _value_ is a constant, all elements are given the same datum; otherwise, if the _value_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). The function is then used to set each element’s new data. A null value will delete the bound data.

If a _value_ is not specified, returns the bound datum for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element.

This method is useful for accessing HTML5 [custom data attributes](http://www.w3.org/TR/html5/dom.html#custom-data-attribute). For example, given the following elements:

html

```
<ul id="list">
  <li data-username="shawnbot">Shawn Allen</li>
  <li data-username="mbostock">Mike Bostock</li>
</ul>
```

You can expose the custom data attributes by setting each element’s data as the built-in [dataset](http://www.w3.org/TR/html5/dom.html#dom-dataset) property:

js

```
selection.datum(function() { return this.dataset; })
```

## _selection_.merge( _other_) [​](https://d3js.org/d3-selection/joining\#selection_merge)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/merge.js) · Returns a new selection merging this selection with the specified _other_ selection or transition. The returned selection has the same number of groups and the same parents as this selection. Any missing (null) elements in this selection are filled with the corresponding element, if present (not null), from the specified _selection_. (If the _other_ selection has additional groups or parents, they are ignored.)

This method is used internally by [_selection_.join](https://d3js.org/d3-selection/joining#selection_join) to merge the [enter](https://d3js.org/d3-selection/joining#selection_enter) and [update](https://d3js.org/d3-selection/joining#selection_data) selections after binding data. You can also merge explicitly, although note that since merging is based on element index, you should use operations that preserve index, such as [_selection_.select](https://d3js.org/d3-selection/selecting#selection_select) instead of [_selection_.filter](https://d3js.org/d3-selection/selecting#selection_filter). For example:

js

```
const odd = selection.select(function(d, i) { return i & 1 ? this : null; ));
const even = selection.select(function(d, i) { return i & 1 ? null : this; ));
const merged = odd.merge(even);
```

See [_selection_.data](https://d3js.org/d3-selection/joining#selection_data) for more.

This method is not intended for concatenating arbitrary selections, however: if both this selection and the specified _other_ selection have (non-null) elements at the same index, this selection’s element is returned in the merge and the _other_ selection’s element is ignored.

## D3.js Threshold Scales
[Skip to content](https://d3js.org/d3-scale/threshold#VPContent)

On this page

# Threshold scales [​](https://d3js.org/d3-scale/threshold\#threshold-scales)

Threshold scales are similar to [quantize scales](https://d3js.org/d3-scale/quantize), except they allow you to map arbitrary subsets of the domain to discrete values in the range. The input domain is still continuous, and divided into slices based on a set of threshold values. See [this choropleth](https://observablehq.com/@d3/threshold-choropleth) for an example.

## scaleThreshold( _domain_, _range_) [​](https://d3js.org/d3-scale/threshold\#scaleThreshold)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/threshold.js) · Constructs a new threshold scale with the specified [_domain_](https://d3js.org/d3-scale/threshold#threshold_domain) and [_range_](https://d3js.org/d3-scale/threshold#threshold_range).

js

```
const color = d3.scaleThreshold([0, 1], ["red", "white", "blue"]);
```

If _domain_ is not specified, it defaults to \[0.5\].

js

```
const color = d3.scaleThreshold(["red", "blue"]);
color(0); // "red"
color(1); // "blue"
```

If _range_ is not specified, it defaults to \[0, 1\].

## _threshold_( _value_) [​](https://d3js.org/d3-scale/threshold\#_threshold)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/threshold.js) · Given a _value_ in the input [domain](https://d3js.org/d3-scale/threshold#threshold_domain), returns the corresponding value in the output [range](https://d3js.org/d3-scale/threshold#threshold_range). For example:

js

```
const color = d3.scaleThreshold([0, 1], ["red", "white", "green"]);
color(-1); // "red"
color(0); // "white"
color(0.5); // "white"
color(1); // "green"
color(1000); // "green"
```

## _threshold_.invertExtent( _value_) [​](https://d3js.org/d3-scale/threshold\#threshold_invertExtent)

[Source](https://github.com/d3/d3-scale/blob/main/src/threshold.js) · Returns the extent of values in the [domain](https://d3js.org/d3-scale/threshold#threshold_domain) \[ _x0_, _x1_\] for the corresponding _value_ in the [range](https://d3js.org/d3-scale/threshold#threshold_range), representing the inverse mapping from range to domain.

js

```
const color = d3.scaleThreshold([0, 1], ["red", "white", "green"]);
color.invertExtent("red"); // [undefined, 0]
color.invertExtent("white"); // [0, 1]
color.invertExtent("green"); // [1, undefined]
```

This method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse. The extent below the lowest threshold is undefined (unbounded), as is the extent above the highest threshold.

## _threshold_.domain( _domain_) [​](https://d3js.org/d3-scale/threshold\#threshold_domain)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/threshold.js) · If _domain_ is specified, sets the scale’s domain to the specified array of values.

js

```
const color = d3.scaleThreshold(["red", "white", "green"]).domain([0, 1]);
```

The values must be in ascending order or the behavior of the scale is undefined. The values are typically numbers, but any naturally ordered values (such as strings) will work; a threshold scale can be used to encode any type that is ordered. If the number of values in the scale’s range is _n_ \+ 1, the number of values in the scale’s domain must be _n_. If there are fewer than _n_ elements in the domain, the additional values in the range are ignored. If there are more than _n_ elements in the domain, the scale may return undefined for some inputs.

If _domain_ is not specified, returns the scale’s current domain.

js

```
color.domain() // [0, 1]
```

## _threshold_.range( _range_) [​](https://d3js.org/d3-scale/threshold\#threshold_range)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/threshold.js) · If _range_ is specified, sets the scale’s range to the specified array of values.

js

```
const color = d3.scaleThreshold().range(["red", "white", "green"]);
```

If the number of values in the scale’s domain is _n_, the number of values in the scale’s range must be _n_ \+ 1\. If there are fewer than _n_ \+ 1 elements in the range, the scale may return undefined for some inputs. If there are more than _n_ \+ 1 elements in the range, the additional values are ignored. The elements in the given array need not be numbers; any value or type will work.

If _range_ is not specified, returns the scale’s current range.

js

```
color.range() // ["red", "white", "green"]
```

## _threshold_.copy() [​](https://d3js.org/d3-scale/threshold\#threshold_copy)

[Examples](https://observablehq.com/@d3/quantile-quantize-and-threshold-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/threshold.js) · Returns an exact copy of this scale.

js

```
const c1 = d3.scaleThreshold(d3.schemeBlues[5]);
const c2 = c1.copy();
```

Changes to this scale will not affect the returned scale, and vice versa.

## Radial Link Generator
[Skip to content](https://d3js.org/d3-shape/radial-link#VPContent)

On this page

# Radial links [​](https://d3js.org/d3-shape/radial-link\#radial-links)

A radial link generator is like the Cartesian [link generator](https://d3js.org/d3-shape/link) except the [x](https://d3js.org/d3-shape/link#link_x) and [y](https://d3js.org/d3-shape/link#link_y) accessors are replaced with [angle](https://d3js.org/d3-shape/radial-link#linkRadial_angle) and [radius](https://d3js.org/d3-shape/radial-link#linkRadial_radius) accessors. Radial links are positioned relative to the origin; use a [transform](http://www.w3.org/TR/SVG/coords.html#TransformAttribute) to change the origin.

## linkRadial() [​](https://d3js.org/d3-shape/radial-link\#linkRadial)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · Returns a new [link generator](https://d3js.org/d3-shape/link#_link) with radial tangents. For example, to visualize [links](https://d3js.org/d3-hierarchy/hierarchy#node_links) in a [tree diagram](https://d3js.org/d3-hierarchy/tree) rooted in the center of the display, you might say:

js

```
const link = d3.linkRadial()
    .angle((d) => d.x)
    .radius((d) => d.y);
```

## _linkRadial_.angle( _angle_) [​](https://d3js.org/d3-shape/radial-link\#linkRadial_angle)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · Equivalent to [_link_.x](https://d3js.org/d3-shape/link#link_x), except the accessor returns the angle in radians, with 0 at - _y_ (12 o’clock).

## _linkRadial_.radius( _radius_) [​](https://d3js.org/d3-shape/radial-link\#linkRadial_radius)

[Source](https://github.com/d3/d3-shape/blob/main/src/link.js) · Equivalent to [_link_.y](https://d3js.org/d3-shape/link#link_y), except the accessor returns the radius: the distance from the origin.

## Point Scales Overview
[Skip to content](https://d3js.org/d3-scale/point#VPContent)

On this page

# Point scales [​](https://d3js.org/d3-scale/point\#point-scales)

Point scales are a variant of [band scales](https://d3js.org/d3-scale/band) with the bandwidth fixed to zero. Point scales are typically used for scatterplots with an ordinal or categorical dimension.

## scalePoint( _domain_, _range_) [​](https://d3js.org/d3-scale/point\#scalePoint)

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Constructs a new point scale with the specified [_domain_](https://d3js.org/d3-scale/point#point_domain) and [_range_](https://d3js.org/d3-scale/point#point_range), no [padding](https://d3js.org/d3-scale/point#point_padding), no [rounding](https://d3js.org/d3-scale/point#point_round) and center [alignment](https://d3js.org/d3-scale/point#point_align). If _domain_ is not specified, it defaults to the empty domain. If _range_ is not specified, it defaults to the unit range \[0, 1\].

## _point_( _value_) [​](https://d3js.org/d3-scale/point\#_point)

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Given a _value_ in the input [domain](https://d3js.org/d3-scale/point#point_domain), returns the corresponding point derived from the output [range](https://d3js.org/d3-scale/point#point_range).

js

```
const x = d3.scalePoint(["a", "b", "c"], [0, 960]);
x("a"); // 0
x("b"); // 480
x("c"); // 960
x("d"); // undefined
```

If the given _value_ is not in the scale’s domain, returns undefined.

## _point_.domain( _domain_) [​](https://d3js.org/d3-scale/point\#point_domain)

Domain:

abcdef

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _domain_ is specified, sets the domain to the specified array of values.

js

```
const x = d3.scalePoint([0, 960]).domain(["a", "b", "c", "d", "e", "f"]);
```

The first element in _domain_ will be mapped to the first point, the second domain value to the second point, and so on. Domain values are stored internally in an [InternMap](https://d3js.org/d3-array/intern) from primitive value to index; the resulting index is then used to determine the point. Thus, a point scale’s values must be coercible to a primitive value, and the primitive domain value uniquely identifies the corresponding point. If _domain_ is not specified, this method returns the current domain.

## _point_.range( _range_) [​](https://d3js.org/d3-scale/point\#point_range)

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _range_ is specified, sets the scale’s range to the specified two-element array of numbers and returns this scale.

js

```
const x = d3.scalePoint().range([0, 960]);
```

If the elements in the given array are not numbers, they will be coerced to numbers. If _range_ is not specified, returns the scale’s current range, which defaults to \[0, 1\].

## _point_.rangeRound( _range_) [​](https://d3js.org/d3-scale/point\#point_rangeRound)

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Sets the scale’s [_range_](https://d3js.org/d3-scale/point#point_range) to the specified two-element array of numbers while also enabling [rounding](https://d3js.org/d3-scale/point#point_round); returns this scale.

js

```
const x = d3.scalePoint().rangeRound([0, 960]);
```

This is a convenience method equivalent to:

js

```
point.range(range).round(true)
```

Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the [shape-rendering](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering) “crispEdges” styles.

## _point_.round( _round_) [​](https://d3js.org/d3-scale/point\#point_round)

Round:

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _round_ is specified, enables or disables rounding accordingly.

js

```
const x = d3.scalePoint(["a", "b", "c"], [0, 960]).round(false);
```

If _round_ is not specified, returns whether rounding is enabled.

js

```
x.round() // false
```

If rounding is enabled, the position of each point will be integers. Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the [shape-rendering](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering) “crispEdges” styles. Note that if the width of the domain is not a multiple of the cardinality of the range, there may be leftover unused space, even without padding! Use [_point_.align](https://d3js.org/d3-scale/point#point_align) to specify how the leftover space is distributed.

## _point_.padding( _padding_) [​](https://d3js.org/d3-scale/point\#point_padding)

Padding:0.10

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _padding_ is specified, sets the outer padding to the specified number which is typically in the range \[0, 1\].

js

```
const x = d3.scalePoint(["a", "b", "c"], [0, 960]).padding(0.1);
```

If _padding_ is not specified, returns the current outer padding which defaults to 0.

js

```
x.padding() // 0.1
```

The outer padding specifies the amount of blank space, in terms of multiples of the [step](https://d3js.org/d3-scale/band#band_step), to reserve before the first point and after the last point. Equivalent to [_band_.paddingOuter](https://d3js.org/d3-scale/band#band_paddingOuter).

## _point_.align( _align_) [​](https://d3js.org/d3-scale/point\#point_align)

Align:0.50

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · If _align_ is specified, sets the alignment to the specified value which must be in the range \[0, 1\].

js

```
const x = d3.scalePoint(["a", "b", "c"], [0, 960]).align(0.5);
```

If _align_ is not specified, returns the current alignment which defaults to 0.5.

js

```
x.align() // 0.5
```

The alignment specifies how any leftover unused space in the range is distributed. A value of 0.5 indicates that the leftover space should be equally distributed before the first point and after the last point; _i.e._, the points should be centered within the range. A value of 0 or 1 may be used to shift the points to one side, say to position them adjacent to an axis.

## _point_.bandwidth() [​](https://d3js.org/d3-scale/point\#point_bandwidth)

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Returns zero.

## _point_.step() [​](https://d3js.org/d3-scale/point\#point_step)

abcdefghij

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Returns the distance between adjacent points.

## _point_.copy() [​](https://d3js.org/d3-scale/point\#point_copy)

[Examples](https://observablehq.com/@d3/d3-scalepoint) · [Source](https://github.com/d3/d3-scale/blob/main/src/band.js) · Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa.

## D3 Transitions Guide
[Skip to content](https://d3js.org/d3-transition#VPContent)

Return to top

# d3-transition [​](https://d3js.org/d3-transition\#d3-transition)

A transition is a [selection](https://d3js.org/d3-selection)-like interface for animating changes to the DOM. Instead of applying changes instantaneously, transitions smoothly interpolate the DOM from its current state to the desired target state over a given duration.

To apply a transition, select elements, call [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition), and then make the desired changes. For example:

js

```
d3.select("body")
  .transition()
    .style("background-color", "red");
```

Transitions support most selection methods (such as [_transition_.attr](https://d3js.org/d3-transition/modifying#transition_attr) and [_transition_.style](https://d3js.org/d3-transition/modifying#transition_style) in place of [_selection_.attr](https://d3js.org/d3-selection/modifying#selection_attr) and [_selection_.style](https://d3js.org/d3-selection/modifying#selection_style)), but not all methods are supported; for example, you must [append](https://d3js.org/d3-selection/modifying#selection_append) elements or [bind data](https://d3js.org/d3-selection/joining) before a transition starts. A [_transition_.remove](https://d3js.org/d3-transition/modifying#transition_remove) operator is provided for convenient removal of elements when the transition ends.

To compute intermediate state, transitions leverage a variety of [built-in interpolators](https://d3js.org/d3-interpolate). [Colors](https://d3js.org/d3-interpolate/color#interpolateRgb), [numbers](https://d3js.org/d3-interpolate/value#interpolateNumber), and [transforms](https://d3js.org/d3-interpolate/transform) are automatically detected. [Strings](https://d3js.org/d3-interpolate/value#interpolateString) with embedded numbers are also detected, as is common with many styles (such as padding or font sizes) and paths. To specify a custom interpolator, use [_transition_.attrTween](https://d3js.org/d3-transition/modifying#transition_attrTween), [_transition_.styleTween](https://d3js.org/d3-transition/modifying#transition_styleTween) or [_transition_.tween](https://d3js.org/d3-transition/modifying#transition_tween).

See one of:

- [Selecting elements](https://d3js.org/d3-transition/selecting)
- [Modifying elements](https://d3js.org/d3-transition/modifying)
- [Timing](https://d3js.org/d3-transition/timing)
- [Control flow](https://d3js.org/d3-transition/control-flow)

## D3.js Color Interpolation
[Skip to content](https://d3js.org/d3-interpolate/color#VPContent)

On this page

# Color interpolation [​](https://d3js.org/d3-interpolate/color\#color-interpolation)

Interpolators for colors in various color spaces.

## interpolateRgb( _a_, _b_) [​](https://d3js.org/d3-interpolate/color\#interpolateRgb)

js

```
d3.interpolateRgb("purple", "orange")
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/rgb.js) · Returns an RGB color space interpolator between the two colors _a_ and _b_ with a configurable [gamma](https://d3js.org/d3-interpolate/color#interpolateColor_gamma). If the gamma is not specified, it defaults to 1.0. The colors _a_ and _b_ need not be in RGB; they will be converted to RGB using [d3.rgb](https://d3js.org/d3-color#rgb). The return value of the interpolator is an RGB string.

## interpolateRgbBasis( _colors_) [​](https://d3js.org/d3-interpolate/color\#interpolateRgbBasis)

js

```
d3.interpolateRgbBasis(["purple", "green", "orange"])
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/rgb.js) · Returns a uniform nonrational B-spline interpolator through the specified array of _colors_, which are converted to [RGB color space](https://d3js.org/d3-color#rgb). Implicit control points are generated such that the interpolator returns _colors_\[0\] at _t_ = 0 and _colors_\[ _colors_.length - 1\] at _t_ = 1\. Opacity interpolation is not currently supported. See also [d3.interpolateBasis](https://d3js.org/d3-interpolate/value#interpolateBasis), and see [d3-scale-chromatic](https://d3js.org/d3-scale-chromatic) for examples.

## interpolateRgbBasisClosed( _colors_) [​](https://d3js.org/d3-interpolate/color\#interpolateRgbBasisClosed)

js

```
d3.interpolateRgbBasisClosed(["purple", "green", "orange"])
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/rgb.js) · Returns a uniform nonrational B-spline interpolator through the specified array of _colors_, which are converted to [RGB color space](https://d3js.org/d3-color#rgb). The control points are implicitly repeated such that the resulting spline has cyclical C² continuity when repeated around _t_ in \[0,1\]; this is useful, for example, to create cyclical color scales. Opacity interpolation is not currently supported. See also [d3.interpolateBasisClosed](https://d3js.org/d3-interpolate/value#interpolateBasisClosed), and see [d3-scale-chromatic](https://d3js.org/d3-scale-chromatic) for examples.

## interpolateHsl( _a_, _b_) [​](https://d3js.org/d3-interpolate/color\#interpolateHsl)

js

```
d3.interpolateHsl("purple", "orange")
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/hsl.js) · Returns an HSL color space interpolator between the two colors _a_ and _b_. The colors _a_ and _b_ need not be in HSL; they will be converted to HSL using [d3.hsl](https://d3js.org/d3-color#hsl). If either color’s hue or saturation is NaN, the opposing color’s channel value is used. The shortest path between hues is used. The return value of the interpolator is an RGB string.

## interpolateHslLong( _a_, _b_) [​](https://d3js.org/d3-interpolate/color\#interpolateHslLong)

js

```
d3.interpolateHslLong("purple", "orange")
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/hsl.js) · Like [interpolateHsl](https://d3js.org/d3-interpolate/color#interpolateHsl), but does not use the shortest path between hues.

## interpolateLab( _a_, _b_) [​](https://d3js.org/d3-interpolate/color\#interpolateLab)

js

```
d3.interpolateLab("purple", "orange")
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/lab.js) · Returns a [CIELAB color space](https://en.wikipedia.org/wiki/Lab_color_space#CIELAB) interpolator between the two colors _a_ and _b_. The colors _a_ and _b_ need not be in CIELAB; they will be converted to CIELAB using [d3.lab](https://d3js.org/d3-color#lab). The return value of the interpolator is an RGB string.

## interpolateHcl( _a_, _b_) [​](https://d3js.org/d3-interpolate/color\#interpolateHcl)

js

```
d3.interpolateHcl("purple", "orange")
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/hcl.js) · Returns a [CIELChab color space](https://en.wikipedia.org/wiki/CIELAB_color_space#Cylindrical_representation:_CIELCh_or_CIEHLC) interpolator between the two colors _a_ and _b_. The colors _a_ and _b_ need not be in CIELChab; they will be converted to CIELChab using [d3.hcl](https://d3js.org/d3-color#hcl). If either color’s hue or chroma is NaN, the opposing color’s channel value is used. The shortest path between hues is used. The return value of the interpolator is an RGB string.

## interpolateHclLong( _a_, _b_) [​](https://d3js.org/d3-interpolate/color\#interpolateHclLong)

js

```
d3.interpolateHclLong("purple", "orange")
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/hcl.js) · Like [interpolateHcl](https://d3js.org/d3-interpolate/color#interpolateHcl), but does not use the shortest path between hues.

## interpolateCubehelix( _a_, _b_) [​](https://d3js.org/d3-interpolate/color\#interpolateCubehelix)

js

```
d3.interpolateCubehelix("purple", "orange")
```

js

```
d3.interpolateCubehelix.gamma(3)("purple", "orange")
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/cubehelix.js) · Returns a Cubehelix color space interpolator between the two colors _a_ and _b_ using a configurable [gamma](https://d3js.org/d3-interpolate/color#interpolateColor_gamma). If the gamma is not specified, it defaults to 1.0. The colors _a_ and _b_ need not be in Cubehelix; they will be converted to Cubehelix using [d3.cubehelix](https://d3js.org/d3-color#cubehelix). If either color’s hue or saturation is NaN, the opposing color’s channel value is used. The shortest path between hues is used. The return value of the interpolator is an RGB string.

## interpolateCubehelixLong( _a_, _b_) [​](https://d3js.org/d3-interpolate/color\#interpolateCubehelixLong)

js

```
d3.interpolateCubehelixLong("purple", "orange")
```

js

```
d3.interpolateCubehelixLong.gamma(3)("purple", "orange")
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/cubehelix.js) · Like [interpolateCubehelix](https://d3js.org/d3-interpolate/color#interpolateCubehelix), but does not use the shortest path between hues.

## _interpolateColor_.gamma( _gamma_) [​](https://d3js.org/d3-interpolate/color\#interpolateColor_gamma)

js

```
d3.interpolateRgb.gamma(2.2)("purple", "orange")
```

Given that _interpolate_ is one of [interpolateRgb](https://d3js.org/d3-interpolate/color#interpolateRgb), [interpolateCubehelix](https://d3js.org/d3-interpolate/color#interpolateCubehelix) or [interpolateCubehelixLong](https://d3js.org/d3-interpolate/color#interpolateCubehelixLong), returns a new interpolator factory of the same type using the specified _gamma_. See Eric Brasseur’s article, [Gamma error in picture scaling](http://www.ericbrasseur.org/gamma.html), for more on gamma correction.

## interpolateHue( _a_, _b_) [​](https://d3js.org/d3-interpolate/color\#interpolateHue)

js

```
d3.interpolateHue(20, 340)(0.5) // 0
```

[Examples](https://observablehq.com/@d3/working-with-color) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/hue.js) · Returns an interpolator between the two hue angles _a_ and _b_. If either hue is NaN, the opposing value is used. The shortest path between hues is used. The return value of the interpolator is a number in \[0, 360).\
\
Whereas standard interpolators blend from a starting value _a_ at _t_ = 0 to an ending value _b_ at _t_ = 1, spline interpolators smoothly blend multiple input values for _t_ in \[0,1\] using piecewise polynomial functions. Only cubic uniform nonrational [B-splines](https://en.wikipedia.org/wiki/B-spline) are currently supported, also known as basis splines.

## D3 Zoom Interpolation
[Skip to content](https://d3js.org/d3-interpolate/zoom#VPContent)

On this page

# Zoom interpolation [​](https://d3js.org/d3-interpolate/zoom\#zoom-interpolation)

An interpolator for zooming smoothly between two views of a two-dimensional plane based on [“Smooth and efficient zooming and panning”](http://www.win.tue.nl/~vanwijk/zoompan.pdf) by Jarke J. van Wijk and Wim A.A. Nuij.

## interpolateZoom( _a_, _b_) [​](https://d3js.org/d3-interpolate/zoom\#interpolateZoom)

js

```
d3.interpolateZoom([30, 30, 40], [135, 85, 60])(0.5) // [72, 52, 126.04761005270991]
```

[Examples](https://observablehq.com/@d3/d3-interpolatezoom) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/zoom.js) · Returns an interpolator between the two views _a_ and _b_. Each view is defined as an array of three numbers: _cx_, _cy_ and _width_. The first two coordinates _cx_, _cy_ represent the center of the viewport; the last coordinate _width_ represents the size of the viewport.

The returned interpolator exposes a _interpolate_.duration property which encodes the recommended transition duration in milliseconds. This duration is based on the path length of the curved trajectory through _xy_ space. If you want a slower or faster transition, multiply this by an arbitrary scale factor ( _V_ as described in the original paper).

## _interpolateZoom_.rho( _rho_) [​](https://d3js.org/d3-interpolate/zoom\#interpolateZoom_rho)

js

```
d3.interpolateZoom.rho(0.5)([30, 30, 40], [135, 85, 60])(0.5) // [72, 52, 51.09549882328188]
```

[Source](https://github.com/d3/d3-interpolate/blob/main/src/zoom.js) · Given a [zoom interpolator](https://d3js.org/d3-interpolate/zoom#interpolateZoom), returns a new zoom interpolator using the specified curvature _rho_. When _rho_ is close to 0, the interpolator is almost linear. The default curvature is sqrt(2).

## D3.js Area Charts
[Skip to content](https://d3js.org/d3-shape/area#VPContent)

On this page

# Areas [​](https://d3js.org/d3-shape/area\#areas)

[Examples](https://observablehq.com/@d3/area-chart/2) · The area generator produces an area defined by a _topline_ and a _baseline_ as in an area chart. Typically, the two lines share the same [_x_-values](https://d3js.org/d3-shape/area#area_x) ( [x0](https://d3js.org/d3-shape/area#area_x0) = [x1](https://d3js.org/d3-shape/area#area_x1)), differing only in _y_-value ( [y0](https://d3js.org/d3-shape/area#area_y0) and [y1](https://d3js.org/d3-shape/area#area_y1)); most commonly, y0 is defined as a constant representing zero (the y scale’s output for zero). The _topline_ is defined by x1 and y1 and is rendered first; the _baseline_ is defined by x0 and y0 and is rendered second with the points in reverse order. With a [curveLinear](https://d3js.org/d3-shape/curve#curveLinear) [curve](https://d3js.org/d3-shape/area#area_curve), this produces a clockwise polygon. See also [radial areas](https://d3js.org/d3-shape/radial-area).

## area( _x_, _y0_, _y1_) [​](https://d3js.org/d3-shape/area\#area)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · Constructs a new area generator with the given _x_, _y0_, and _y1_ accessors or numbers.

js

```
const area = d3.area((d) => x(d.Date), y(0), (d) => y(d.Close));
```

If _x_, _y0_ or _y1_ are not specified, the respective defaults will be used. The above can be expressed more explicitly as:

js

```
const area = d3.area()
    .x((d) => x(d.Date))
    .y0(y(0))
    .y1((d) => y(d.Close));
```

## _area_( _data_) [​](https://d3js.org/d3-shape/area\#_area)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · Generates an area for the given array of _data_.

js

```
svg.append("path").attr("d", area(data));
```

If the area generator has a [context](https://d3js.org/d3-shape/area#area_context), then the area is rendered to this context as a sequence of [path method](http://www.w3.org/TR/2dcontext/#canvaspathmethods) calls and this function returns void. Otherwise, a [path data](http://www.w3.org/TR/SVG/paths.html#PathData) string is returned.

CAUTION

Depending on this area generator’s associated [curve](https://d3js.org/d3-shape/area#area_curve), the given input _data_ may need to be sorted by _x_-value before being passed to the area generator.

## _area_.x( _x_) [​](https://d3js.org/d3-shape/area\#area_x)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · If _x_ is specified, sets [x0](https://d3js.org/d3-shape/area#area_x0) to _x_ and [x1](https://d3js.org/d3-shape/area#area_x1) to null and returns this area generator.

js

```
const area = d3.area().x((d) => x(d.Date));
```

If _x_ is not specified, returns the current x0 accessor.

js

```
area.x() // (d) => x(d.Date)
```

## _area_.x0( _x_) [​](https://d3js.org/d3-shape/area\#area_x0)

TIP

This method is intended for vertically-oriented areas, as when time goes down↓ rather than right→; for the more common horizontally-oriented areas, use [_area_.x](https://d3js.org/d3-shape/area#area_x) instead.

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · If _x_ is specified, sets the x0 accessor to the specified function or number and returns this area generator.

js

```
const area = d3.area().x0(x(0));
```

When an area is [generated](https://d3js.org/d3-shape/area#_area), the x0 accessor will be invoked for each [defined](https://d3js.org/d3-shape/area#area_defined) element in the input data array, being passed the element `d`, the index `i`, and the array `data` as three arguments.

If _x_ is not specified, returns the current x0 accessor.

js

```
area.x0() // () => 20
```

The x0 accessor defaults to:

js

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

The default x0 accessor assumes that the input data are two-element arrays of numbers \[\[x0, y0\], \[x1, y1\], …\]. If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor as shown above.

## _area_.x1( _x_) [​](https://d3js.org/d3-shape/area\#area_x1)

TIP

This method is intended for vertically-oriented areas, as when time goes down↓ rather than right→; for the more common horizontally-oriented areas, use [_area_.x](https://d3js.org/d3-shape/area#area_x) instead.

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · If _x_ is specified, sets the x1 accessor to the specified function or number and returns this area generator.

js

```
const area = d3.area().x1((d) => x(d.Close));
```

When an area is [generated](https://d3js.org/d3-shape/area#_area), the x1 accessor will be invoked for each [defined](https://d3js.org/d3-shape/area#area_defined) element in the input data array, being passed the element `d`, the index `i`, and the array `data` as three arguments.

If _x_ is not specified, returns the current x1 accessor.

js

```
area.x1() // (d) => x(d.Close)
```

The x1 accessor defaults to null, indicating that the previously-computed [x0](https://d3js.org/d3-shape/area#area_x0) value should be reused for the x1 value; this default is intended for horizontally-oriented areas.

## _area_.y( _y_) [​](https://d3js.org/d3-shape/area\#area_y)

TIP

This method is intended for vertically-oriented areas, as when time goes down↓ rather than right→; for the more common horizontally-oriented areas, use [_area_.y0](https://d3js.org/d3-shape/area#area_y0) and [_area_.y1](https://d3js.org/d3-shape/area#area_y1) instead.

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · If _y_ is specified, sets [y0](https://d3js.org/d3-shape/area#area_y0) to _y_ and [y1](https://d3js.org/d3-shape/area#area_y1) to null and returns this area generator.

js

```
const area = d3.area().y((d) => y(d.Date));
```

If _y_ is not specified, returns the current y0 accessor.

js

```
area.y() // (d) => y(d.Date)
```

## _area_.y0( _y_) [​](https://d3js.org/d3-shape/area\#area_y0)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · If _y_ is specified, sets the y0 accessor to the specified function or number and returns this area generator.

js

```
const area = d3.area().y0(y(0));
```

When an area is [generated](https://d3js.org/d3-shape/area#_area), the y0 accessor will be invoked for each [defined](https://d3js.org/d3-shape/area#area_defined) element in the input data array, being passed the element `d`, the index `i`, and the array `data` as three arguments. For a horizontally-oriented area with a constant baseline ( _i.e._, an area that is not stacked, and not a ribbon or band), y0 is typically set to the output of the y scale for zero.

If _y_ is not specified, returns the current y0 accessor.

js

```
area.y0() // () => 360
```

The y0 accessor defaults to:

js

```
function y() {
  return 0;
}
```

In the default SVG coordinate system, note that the default zero represents the top of the chart rather than the bottom, producing a flipped (or “hanging”) area.

## _area_.y1( _y_) [​](https://d3js.org/d3-shape/area\#area_y1)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · If _y_ is specified, sets the y1 accessor to the specified function or number and returns this area generator.

js

```
const area = d3.area().y1((d) => y(d.Close));
```

When an area is [generated](https://d3js.org/d3-shape/area#_area), the y1 accessor will be invoked for each [defined](https://d3js.org/d3-shape/area#area_defined) element in the input data array, being passed the element `d`, the index `i`, and the array `data` as three arguments.

If _y_ is not specified, returns the current y1 accessor.

js

```
area.y1() // (d) => y(d.Close)
```

The y1 accessor defaults to:

js

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

The default y1 accessor assumes that the input data are two-element arrays of numbers \[\[x0, y0\], \[x1, y1\], …\]. If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor as shown above. A null accessor is also allowed, indicating that the previously-computed [y0](https://d3js.org/d3-shape/area#area_y0) value should be reused for the y1 value; this can be used for a vertically-oriented area, as when time goes down↓ instead of right→.

## _area_.defined( _defined_) [​](https://d3js.org/d3-shape/area\#area_defined)

[Examples](https://observablehq.com/@d3/area-chart-missing-data/2) · [Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · If _defined_ is specified, sets the defined accessor to the specified function or boolean and returns this area generator.

js

```
const area = d3.area().defined((d) => !isNaN(d.Close));
```

When an area is [generated](https://d3js.org/d3-shape/area#_area), the defined accessor will be invoked for each element in the input data array, being passed the element `d`, the index `i`, and the array `data` as three arguments. If the given element is defined ( _i.e._, if the defined accessor returns a truthy value for this element), the [x0](https://d3js.org/d3-shape/area#area_x0), [x1](https://d3js.org/d3-shape/area#area_x1), [y0](https://d3js.org/d3-shape/area#area_y0) and [y1](https://d3js.org/d3-shape/area#area_y1) accessors will subsequently be evaluated and the point will be added to the current area segment. Otherwise, the element will be skipped, the current area segment will be ended, and a new area segment will be generated for the next defined point. As a result, the generated area may have several discrete segments.

If _defined_ is not specified, returns the current defined accessor.

js

```
area.defined() // (d) => !isNaN(d.Close)
```

The defined accessor defaults to the constant true, and assumes that the input data is always defined:

js

```
function defined() {
  return true;
}
```

Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square [line caps](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-linecap). In addition, some curves such as [curveCardinalOpen](https://d3js.org/d3-shape/curve#curveCardinalOpen) only render a visible segment if it contains multiple points.

## _area_.curve( _curve_) [​](https://d3js.org/d3-shape/area\#area_curve)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · If _curve_ is specified, sets the [curve factory](https://d3js.org/d3-shape/curve) and returns this area generator.

js

```
const area = d3.area().curve(d3.curveStep);
```

If _curve_ is not specified, returns the current curve factory, which defaults to [curveLinear](https://d3js.org/d3-shape/curve#curveLinear).

js

```
area.curve() // d3.curveStep
```

## _area_.context(context) [​](https://d3js.org/d3-shape/area\#area_context)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · If _context_ is specified, sets the context and returns this area generator.

js

```
const context = canvas.getContext("2d");
const area = d3.area().context(context);
```

If _context_ is not specified, returns the current context.

js

```
area.context() // context
```

The context defaults to null. If the context is not null, then the [generated area](https://d3js.org/d3-shape/area#_area) is rendered to this context as a sequence of [path method](http://www.w3.org/TR/2dcontext/#canvaspathmethods) calls. Otherwise, a [path data](http://www.w3.org/TR/SVG/paths.html#PathData) string representing the generated area is returned.

## _area_.digits(digits) [​](https://d3js.org/d3-shape/area\#area_digits)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · If _digits_ is specified, sets the maximum number of digits after the decimal separator and returns this area generator.

js

```
const area = d3.area().digits(3);
```

If _digits_ is not specified, returns the current maximum fraction digits, which defaults to 3.

js

```
area.digits() // 3
```

This option only applies when the associated [_context_](https://d3js.org/d3-shape/area#area_context) is null, as when this area generator is used to produce [path data](http://www.w3.org/TR/SVG/paths.html#PathData).

## _area_.lineX0() [​](https://d3js.org/d3-shape/area\#area_lineX0)

An alias for [_area_.lineY0](https://d3js.org/d3-shape/area#area_lineY0).

## _area_.lineY0() [​](https://d3js.org/d3-shape/area\#area_lineY0)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · Returns a new [line generator](https://d3js.org/d3-shape/line) that has this area generator’s current [defined accessor](https://d3js.org/d3-shape/area#area_defined), [curve](https://d3js.org/d3-shape/area#area_curve) and [context](https://d3js.org/d3-shape/area#area_context). The line’s [_x_-accessor](https://d3js.org/d3-shape/line#line_x) is this area’s [_x0_-accessor](https://d3js.org/d3-shape/area#area_x0), and the line’s [_y_-accessor](https://d3js.org/d3-shape/line#line_y) is this area’s [_y0_-accessor](https://d3js.org/d3-shape/area#area_y0).

## _area_.lineX1() [​](https://d3js.org/d3-shape/area\#area_lineX1)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · Returns a new [line generator](https://d3js.org/d3-shape/line#lines) that has this area generator’s current [defined accessor](https://d3js.org/d3-shape/area#area_defined), [curve](https://d3js.org/d3-shape/area#area_curve) and [context](https://d3js.org/d3-shape/area#area_context). The line’s [_x_-accessor](https://d3js.org/d3-shape/line#line_x) is this area’s [_x1_-accessor](https://d3js.org/d3-shape/area#area_x1), and the line’s [_y_-accessor](https://d3js.org/d3-shape/line#line_y) is this area’s [_y0_-accessor](https://d3js.org/d3-shape/area#area_y0).

## _area_.lineY1() [​](https://d3js.org/d3-shape/area\#area_lineY1)

[Source](https://github.com/d3/d3-shape/blob/main/src/area.js) · Returns a new [line generator](https://d3js.org/d3-shape/line#lines) that has this area generator’s current [defined accessor](https://d3js.org/d3-shape/area#area_defined), [curve](https://d3js.org/d3-shape/area#area_curve) and [context](https://d3js.org/d3-shape/area#area_context). The line’s [_x_-accessor](https://d3js.org/d3-shape/line#line_x) is this area’s [_x0_-accessor](https://d3js.org/d3-shape/area#area_x0), and the line’s [_y_-accessor](https://d3js.org/d3-shape/line#line_y) is this area’s [_y1_-accessor](https://d3js.org/d3-shape/area#area_y1).

## D3.js Power Scales
[Skip to content](https://d3js.org/d3-scale/pow#VPContent)

Return to top

# Power scales [​](https://d3js.org/d3-scale/pow\#power-scales)

Power (“pow”) scales are similar to [linear scales](https://d3js.org/d3-scale/linear), except an exponential transform is applied to the input domain value before the output range value is computed. Each range value _y_ can be expressed as a function of the domain value _x_: _y_ = _mx^k_ \+ _b_, where _k_ is the [exponent](https://d3js.org/d3-scale/pow#pow_exponent) value. Power scales also support negative domain values, in which case the input value and the resulting output value are multiplied by -1.

### scalePow( _domain_, _range_) [​](https://d3js.org/d3-scale/pow\#scalePow)

[Examples](https://observablehq.com/@d3/continuous-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/pow.js) · Constructs a new pow scale with the specified [domain](https://d3js.org/d3-scale/linear#linear_domain) and [range](https://d3js.org/d3-scale/linear#linear_range), the [exponent](https://d3js.org/d3-scale/pow#pow_exponent) 1, the [default](https://d3js.org/d3-interpolate/value#interpolate) [interpolator](https://d3js.org/d3-scale/linear#linear_interpolate) and [clamping](https://d3js.org/d3-scale/linear#linear_clamp) disabled.

js

```
const x = d3.scalePow([0, 100], ["red", "blue"]).exponent(2);
```

If either _domain_ or _range_ are not specified, each defaults to \[0, 1\].

### scaleSqrt( _domain_, _range_) [​](https://d3js.org/d3-scale/pow\#scaleSqrt)

[Examples](https://observablehq.com/@d3/continuous-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/pow.js) · Constructs a new pow scale with the specified [domain](https://d3js.org/d3-scale/linear#linear_domain) and [range](https://d3js.org/d3-scale/linear#linear_range), the [exponent](https://d3js.org/d3-scale/pow#pow_exponent) 0.5, the [default](https://d3js.org/d3-interpolate/value#interpolate) [interpolator](https://d3js.org/d3-scale/linear#linear_interpolate) and [clamping](https://d3js.org/d3-scale/linear#linear_clamp) disabled.

js

```
const x = d3.scaleSqrt([0, 100], ["red", "blue"]);
```

If either _domain_ or _range_ are not specified, each defaults to \[0, 1\]. This is a convenience method equivalent to `d3.scalePow(…).exponent(0.5)`.

### _pow_.exponent( _exponent_) [​](https://d3js.org/d3-scale/pow\#pow_exponent)

[Examples](https://observablehq.com/@d3/continuous-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/pow.js) · If _exponent_ is specified, sets the current exponent to the given numeric value and returns this scale.

js

```
const x = d3.scalePow([0, 100], ["red", "blue"]).exponent(2);
```

If _exponent_ is not specified, returns the current exponent, which defaults to 1.

js

```
x.exponent() // 2
```

If the _exponent_ is 1, the pow scale is effectively a [linear](https://d3js.org/d3-scale/linear) scale.

## D3.js Diverging Scales
[Skip to content](https://d3js.org/d3-scale/diverging#VPContent)

On this page

# Diverging scales [​](https://d3js.org/d3-scale/diverging\#diverging-scales)

Diverging scales are similar to [linear scales](https://d3js.org/d3-scale/linear) in that they map a continuous, numeric input domain to a continuous output range. Unlike linear scales, the input domain and output range of a diverging scale always have exactly three elements, and the output range is typically specified as an interpolator rather than an array of values. Diverging scales are typically used for a color encoding; see also [d3-scale-chromatic](https://d3js.org/d3-scale-chromatic). These scales do not expose [invert](https://d3js.org/d3-scale/linear#linear_invert) and [interpolate](https://d3js.org/d3-scale/linear#linear_interpolate) methods. There are also [log](https://d3js.org/d3-scale/diverging#scaleDivergingLog), [pow](https://d3js.org/d3-scale/diverging#scaleDivergingPow), and [symlog](https://d3js.org/d3-scale/diverging#scaleDivergingSymlog) variants of diverging scales.

## scaleDiverging( _domain_, _interpolator_) [​](https://d3js.org/d3-scale/diverging\#scaleDiverging)

[Examples](https://observablehq.com/@d3/diverging-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/diverging.js) · Constructs a new diverging scale with the specified [_domain_](https://d3js.org/d3-scale/linear#linear_domain) and [_interpolator_](https://d3js.org/d3-scale/diverging#diverging_interpolator) function or array.

js

```
const color = d3.scaleDiverging([-1, 0, 1], d3.interpolateRdBu);
```

If _domain_ is not specified, it defaults to \[0, 0.5, 1\].

js

```
const color = d3.scaleDiverging(d3.interpolateRdBu);
```

If _interpolator_ is not specified, it defaults to the identity function.

js

```
const identity = d3.scaleDiverging();
```

When the scale is applied, the interpolator will be invoked with a value typically in the range \[0, 1\], where 0 represents the extreme negative value, 0.5 represents the neutral value, and 1 represents the extreme positive value.

If _interpolator_ is an array, it represents the scale’s three-element output range and is converted to an interpolator function using [d3.interpolate](https://d3js.org/d3-interpolate/value#interpolate) and [d3.piecewise](https://d3js.org/d3-interpolate/value#piecewise).

js

```
const color = d3.scaleDiverging(["blue", "white", "red"]);
```

A diverging scale’s domain must be numeric and must contain exactly three values.

## _diverging_.interpolator( _interpolator_) [​](https://d3js.org/d3-scale/diverging\#diverging_interpolator)

If _interpolator_ is specified, sets the scale’s interpolator to the specified function.

js

```
const color = d3.scaleDiverging().interpolator(d3.interpolateRdBu);
```

If _interpolator_ is not specified, returns the scale’s current interpolator.

js

```
color.interpolator() // d3.interpolateRdBu
```

## _diverging_.range( _range_) [​](https://d3js.org/d3-scale/diverging\#diverging_range)

See [_linear_.range](https://d3js.org/d3-scale/linear#linear_range). If _range_ is specified, the given three-element array is converted to an interpolator function using [piecewise](https://d3js.org/d3-interpolate/value#piecewise).

js

```
const color = d3.scaleDiverging().range(["blue", "white", "red"]);
```

The above is equivalent to:

js

```
const color = d3.scaleDiverging(d3.piecewise(["blue", "white", "red"]));
```

## _diverging_.rangeRound( _range_) [​](https://d3js.org/d3-scale/diverging\#diverging_rangeRound)

See [_linear_.range](https://d3js.org/d3-scale/linear#linear_rangeRound). If _range_ is specified, implicitly uses [interpolateRound](https://d3js.org/d3-interpolate/value#interpolateRound) as the interpolator.

## scaleDivergingLog( _domain_, _range_) [​](https://d3js.org/d3-scale/diverging\#scaleDivergingLog)

Returns a new diverging scale with a logarithmic transform, analogous to a [log scale](https://d3js.org/d3-scale/log).

## scaleDivergingPow( _domain_, _range_) [​](https://d3js.org/d3-scale/diverging\#scaleDivergingPow)

Returns a new diverging scale with an exponential transform, analogous to a [power scale](https://d3js.org/d3-scale/pow).

## scaleDivergingSqrt( _domain_, _range_) [​](https://d3js.org/d3-scale/diverging\#scaleDivergingSqrt)

Returns a new diverging scale with a square-root transform, analogous to a [sqrt scale](https://d3js.org/d3-scale/pow#scaleSqrt).

## scaleDivergingSymlog( _domain_, _range_) [​](https://d3js.org/d3-scale/diverging\#scaleDivergingSymlog)

Returns a new diverging scale with a symmetric logarithmic transform, analogous to a [symlog scale](https://d3js.org/d3-scale/symlog).

## D3.js Line Generator
[Skip to content](https://d3js.org/d3-shape/line#VPContent)

On this page

# Lines [​](https://d3js.org/d3-shape/line\#lines)

[Examples](https://observablehq.com/@d3/line-chart/2) · The line generator produces a [spline](https://en.wikipedia.org/wiki/Spline_(mathematics)) or [polyline](https://en.wikipedia.org/wiki/Polygonal_chain) as in a line chart. Lines also appear in many other visualization types, such as the links in [hierarchical edge bundling](https://observablehq.com/@d3/hierarchical-edge-bundling). See also [radial lines](https://d3js.org/d3-shape/radial-line).

## line( _x_, _y_) [​](https://d3js.org/d3-shape/line\#line)

[Source](https://github.com/d3/d3-shape/blob/main/src/line.js) · Constructs a new line generator with the given _x_ and _y_ accessor.

js

```
const line = d3.line((d) => x(d.Date), (d) => y(d.Close));
```

If _x_ or _y_ are not specified, the respective defaults will be used. The above can be expressed more explicitly as:

js

```
const line = d3.line()
    .x((d) => x(d.Date))
    .y((d) => y(d.Close));
```

## _line_( _data_) [​](https://d3js.org/d3-shape/line\#_line)

[Source](https://github.com/d3/d3-shape/blob/main/src/line.js) · Generates a line for the given array of _data_.

js

```
svg.append("path").attr("d", line(data)).attr("stroke", "currentColor");
```

If the line generator has a [context](https://d3js.org/d3-shape/line#line_context), then the line is rendered to this context as a sequence of [path method](http://www.w3.org/TR/2dcontext/#canvaspathmethods) calls and this function returns void. Otherwise, a [path data](http://www.w3.org/TR/SVG/paths.html#PathData) string is returned.

CAUTION

Depending on this line generator’s associated [curve](https://d3js.org/d3-shape/line#line_curve), the given input _data_ may need to be sorted by _x_-value before being passed to the line generator.

## _line_.x( _x_) [​](https://d3js.org/d3-shape/line\#line_x)

[Source](https://github.com/d3/d3-shape/blob/main/src/line.js) · If _x_ is specified, sets the x accessor to the specified function or number and returns this line generator.

js

```
const line = d3.line().x((d) => x(d.Date));
```

If _x_ is not specified, returns the current x accessor.

js

```
line.x() // (d) => x(d.Date)
```

The x accessor defaults to:

js

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

When a line is [generated](https://d3js.org/d3-shape/line#_line), the x accessor will be invoked for each [defined](https://d3js.org/d3-shape/line#line_defined) element in the input data array, being passed the element `d`, the index `i`, and the array `data` as three arguments.

The default x accessor assumes that the input data are two-element arrays of numbers. If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor.

## _line_.y(y) [​](https://d3js.org/d3-shape/line\#line_y)

[Source](https://github.com/d3/d3-shape/blob/main/src/line.js) · If _y_ is specified, sets the y accessor to the specified function or number and returns this line generator.

js

```
const line = d3.line().y((d) => y(d.Close));
```

When a line is [generated](https://d3js.org/d3-shape/line#_line), the y accessor will be invoked for each [defined](https://d3js.org/d3-shape/line#line_defined) element in the input data array, being passed the element `d`, the index `i`, and the array `data` as three arguments.

If _y_ is not specified, returns the current y accessor.

js

```
line.y() // (d) => y(d.Close)
```

The y accessor defaults to:

js

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

The default y accessor assumes that the input data are two-element arrays of numbers. See [_line_.x](https://d3js.org/d3-shape/line#line_x) for more information.

## _line_.defined( _defined_) [​](https://d3js.org/d3-shape/line\#line_defined)

[Examples](https://observablehq.com/@d3/line-chart-missing-data/2) · [Source](https://github.com/d3/d3-shape/blob/main/src/line.js) · If _defined_ is specified, sets the defined accessor to the specified function or boolean and returns this line generator.

js

```
const line = d3.line().defined((d) => !isNaN(d.Close));
```

When a line is [generated](https://d3js.org/d3-shape/line#_line), the defined accessor will be invoked for each element in the input data array, being passed the element `d`, the index `i`, and the array `data` as three arguments. If the given element is defined ( _i.e._, if the defined accessor returns a truthy value for this element), the [x](https://d3js.org/d3-shape/line#line_x) and [y](https://d3js.org/d3-shape/line#line_y) accessors will subsequently be evaluated and the point will be added to the current line segment. Otherwise, the element will be skipped, the current line segment will be ended, and a new line segment will be generated for the next defined point.

If _defined_ is not specified, returns the current defined accessor.

js

```
line.defined() // (d) => !isNaN(d.Close)
```

The defined accessor defaults to the constant true, and assumes that the input data is always defined:

js

```
function defined() {
  return true;
}
```

Note that if a line segment consists of only a single point, it may appear invisible unless rendered with rounded or square [line caps](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-linecap). In addition, some curves such as [curveCardinalOpen](https://d3js.org/d3-shape/curve#curveCardinalOpen) only render a visible segment if it contains multiple points.

## _line_.curve( _curve_) [​](https://d3js.org/d3-shape/line\#line_curve)

[Source](https://github.com/d3/d3-shape/blob/main/src/line.js) · If _curve_ is specified, sets the [curve factory](https://d3js.org/d3-shape/curve) and returns this line generator.

js

```
const line = d3.line().curve(d3.curveStep);
```

If _curve_ is not specified, returns the current curve factory, which defaults to [curveLinear](https://d3js.org/d3-shape/curve#curveLinear).

js

```
line.curve() // d3.curveStep
```

## _line_.context(context) [​](https://d3js.org/d3-shape/line\#line_context)

[Source](https://github.com/d3/d3-shape/blob/main/src/line.js) · If _context_ is specified, sets the context and returns this line generator.

js

```
const context = canvas.getContext("2d");
const line = d3.line().context(context);
```

If _context_ is not specified, returns the current context.

js

```
line.context() // context
```

The context defaults to null. If the context is not null, then the [generated line](https://d3js.org/d3-shape/line#_line) is rendered to this context as a sequence of [path method](http://www.w3.org/TR/2dcontext/#canvaspathmethods) calls. Otherwise, a [path data](http://www.w3.org/TR/SVG/paths.html#PathData) string representing the generated line is returned.

## _line_.digits( _digits_) [​](https://d3js.org/d3-shape/line\#line_digits)

[Source](https://github.com/d3/d3-shape/blob/main/src/line.js) · If _digits_ is specified, sets the maximum number of digits after the decimal separator and returns this line generator.

js

```
const line = d3.line().digits(3);
```

If _digits_ is not specified, returns the current maximum fraction digits, which defaults to 3.

js

```
line.digits() // 3
```

This option only applies when the associated [_context_](https://d3js.org/d3-shape/line#line_context) is null, as when this line generator is used to produce [path data](http://www.w3.org/TR/SVG/paths.html#PathData).

## D3.js Spherical Shapes
[Skip to content](https://d3js.org/d3-geo/shape#VPContent)

On this page

# Spherical shapes [​](https://d3js.org/d3-geo/shape\#spherical-shapes)

These shape generators return spherical GeoJSON for use with [geoPath](https://d3js.org/d3-geo/path).

TIP

To generate a [great arc](https://en.wikipedia.org/wiki/Great-circle_distance) (a segment of a great circle), pass a GeoJSON LineString geometry object to a [geoPath](https://d3js.org/d3-geo/path). D3’s projections use geodesic interpolation for intermediate points.

## geoGraticule() [​](https://d3js.org/d3-geo/shape\#geoGraticule)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · Constructs a geometry generator for creating graticules: a uniform grid of [meridians](https://en.wikipedia.org/wiki/Meridian_(geography)) and [parallels](https://en.wikipedia.org/wiki/Circle_of_latitude) for showing projection distortion. The default graticule has meridians and parallels every 10° between ±80° latitude; for the polar regions, there are meridians every 90°.

## _graticule_() [​](https://d3js.org/d3-geo/shape\#_graticule)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · Returns a GeoJSON MultiLineString geometry object representing all meridians and parallels for this graticule.

## _graticule_.lines() [​](https://d3js.org/d3-geo/shape\#graticule_lines)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · Returns an array of GeoJSON LineString geometry objects, one for each meridian or parallel for this graticule.

## _graticule_.outline() [​](https://d3js.org/d3-geo/shape\#graticule_outline)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · Returns a GeoJSON Polygon geometry object representing the outline of this graticule, i.e. along the meridians and parallels defining its extent.

## _graticule_.extent( _extent_) [​](https://d3js.org/d3-geo/shape\#graticule_extent)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · If _extent_ is specified, sets the major and minor extents of this graticule. If _extent_ is not specified, returns the current minor extent, which defaults to ⟨⟨-180°, -80° - ε⟩, ⟨180°, 80° + ε⟩⟩.

## _graticule_.extentMajor( _extent_) [​](https://d3js.org/d3-geo/shape\#graticule_extentMajor)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · If _extent_ is specified, sets the major extent of this graticule. If _extent_ is not specified, returns the current major extent, which defaults to ⟨⟨-180°, -90° + ε⟩, ⟨180°, 90° - ε⟩⟩.

## _graticule_.extentMinor( _extent_) [​](https://d3js.org/d3-geo/shape\#graticule_extentMinor)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · If _extent_ is specified, sets the minor extent of this graticule. If _extent_ is not specified, returns the current minor extent, which defaults to ⟨⟨-180°, -80° - ε⟩, ⟨180°, 80° + ε⟩⟩.

## _graticule_.step( _step_) [​](https://d3js.org/d3-geo/shape\#graticule_step)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · If _step_ is specified, sets the major and minor step for this graticule. If _step_ is not specified, returns the current minor step, which defaults to ⟨10°, 10°⟩.

## _graticule_.stepMajor( _step_) [​](https://d3js.org/d3-geo/shape\#graticule_stepMajor)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · If _step_ is specified, sets the major step for this graticule. If _step_ is not specified, returns the current major step, which defaults to ⟨90°, 360°⟩.

## _graticule_.stepMinor( _step_) [​](https://d3js.org/d3-geo/shape\#graticule_stepMinor)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · If _step_ is specified, sets the minor step for this graticule. If _step_ is not specified, returns the current minor step, which defaults to ⟨10°, 10°⟩.

## _graticule_.precision( _angle_) [​](https://d3js.org/d3-geo/shape\#graticule_precision)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · If _precision_ is specified, sets the precision for this graticule, in degrees. If _precision_ is not specified, returns the current precision, which defaults to 2.5°.

## geoGraticule10() [​](https://d3js.org/d3-geo/shape\#geoGraticule10)

[Source](https://github.com/d3/d3-geo/blob/main/src/graticule.js) · A convenience method for directly generating the default 10° global graticule as a GeoJSON MultiLineString geometry object. Equivalent to:

js

```
function geoGraticule10() {
  return d3.geoGraticule()();
}
```

## geoCircle() [​](https://d3js.org/d3-geo/shape\#geoCircle)

[Source](https://github.com/d3/d3-geo/blob/main/src/circle.js) · Returns a new circle generator.

## _circle_(... _arguments_) [​](https://d3js.org/d3-geo/shape\#_circle)

[Source](https://github.com/d3/d3-geo/blob/main/src/circle.js) · Returns a new GeoJSON geometry object of type “Polygon” approximating a circle on the surface of a sphere, with the current [center](https://d3js.org/d3-geo/shape#circle_center), [radius](https://d3js.org/d3-geo/shape#circle_radius) and [precision](https://d3js.org/d3-geo/shape#circle_precision). Any _arguments_ are passed to the accessors.

## _circle_.center( _center_) [​](https://d3js.org/d3-geo/shape\#circle_center)

[Source](https://github.com/d3/d3-geo/blob/main/src/circle.js) · If _center_ is specified, sets the circle center to the specified point \[ _longitude_, _latitude_\] in degrees, and returns this circle generator. The center may also be specified as a function; this function will be invoked whenever a circle is [generated](https://d3js.org/d3-geo/shape#_circle), being passed any arguments passed to the circle generator. If _center_ is not specified, returns the current center accessor, which defaults to:

js

```
function center() {
  return [0, 0];
}
```

## _circle_.radius( _radius_) [​](https://d3js.org/d3-geo/shape\#circle_radius)

[Source](https://github.com/d3/d3-geo/blob/main/src/circle.js) · If _radius_ is specified, sets the circle radius to the specified angle in degrees, and returns this circle generator. The radius may also be specified as a function; this function will be invoked whenever a circle is [generated](https://d3js.org/d3-geo/shape#_circle), being passed any arguments passed to the circle generator. If _radius_ is not specified, returns the current radius accessor, which defaults to:

js

```
function radius() {
  return 90;
}
```

## _circle_.precision( _angle_) [​](https://d3js.org/d3-geo/shape\#circle_precision)

[Source](https://github.com/d3/d3-geo/blob/main/src/circle.js) · If _precision_ is specified, sets the circle precision to the specified angle in degrees, and returns this circle generator. The precision may also be specified as a function; this function will be invoked whenever a circle is [generated](https://d3js.org/d3-geo/shape#_circle), being passed any arguments passed to the circle generator. If _precision_ is not specified, returns the current precision accessor, which defaults to:

js

```
function precision() {
  return 2;
}
```

Small circles do not follow great arcs and thus the generated polygon is only an approximation. Specifying a smaller precision angle improves the accuracy of the approximate polygon, but also increase the cost to generate and render it.

## D3.js Geo Projections
[Skip to content](https://d3js.org/d3-geo/projection#VPContent)

On this page

# Projections [​](https://d3js.org/d3-geo/projection\#projections)

Projections transform spherical polygonal geometry to planar polygonal geometry. D3 provides implementations of several classes of standard projections:

- [Azimuthal projections](https://d3js.org/d3-geo/azimuthal)
- [Conic projections](https://d3js.org/d3-geo/conic)
- [Cylindrical projections](https://d3js.org/d3-geo/cylindrical)

For more projections, see [d3-geo-projection](https://github.com/d3/d3-geo-projection) and [d3-geo-polygon](https://github.com/d3/d3-geo-polygon). You can implement [custom projections](https://d3js.org/d3-geo/projection#raw-projections) using [geoProjection](https://d3js.org/d3-geo/projection#geoProjection) or [geoProjectionMutator](https://d3js.org/d3-geo/projection#geoProjectionMutator).

## _projection_( _point_) [​](https://d3js.org/d3-geo/projection\#_projection)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · Returns a new array \[ _x_, _y_\] (typically in pixels) representing the projected point of the given _point_. The point must be specified as a two-element array \[ _longitude_, _latitude_\] in degrees. May return null if the specified _point_ has no defined projected position, such as when the point is outside the clipping bounds of the projection.

## _projection_.invert( _point_) [​](https://d3js.org/d3-geo/projection\#projection_invert)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · Returns a new array \[ _longitude_, _latitude_\] in degrees representing the unprojected point of the given projected _point_. The point must be specified as a two-element array \[ _x_, _y_\] (typically in pixels). May return null if the specified _point_ has no defined projected position, such as when the point is outside the clipping bounds of the projection.

This method is only defined on invertible projections.

## _projection_.stream( _stream_) [​](https://d3js.org/d3-geo/projection\#projection_stream)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · Returns a [projection stream](https://d3js.org/d3-geo/stream) for the specified output _stream_. Any input geometry is projected before being streamed to the output stream. A typical projection involves several geometry transformations: the input geometry is first converted to radians, rotated on three axes, clipped to the small circle or cut along the antimeridian, and lastly projected to the plane with adaptive resampling, scale and translation.

## _projection_.preclip( _preclip_) [​](https://d3js.org/d3-geo/projection\#projection_preclip)

If _preclip_ is specified, sets the projection’s spherical clipping to the specified function and returns the projection; _preclip_ is a function that takes a [projection stream](https://d3js.org/d3-geo/stream) and returns a clipped stream. If _preclip_ is not specified, returns the current spherical clipping function. Preclipping is commonly used to cut along the antimeridian line or along a small circle.

## _projection_.postclip( _postclip_) [​](https://d3js.org/d3-geo/projection\#projection_postclip)

If _postclip_ is specified, sets the projection’s Cartesian clipping to the specified function and returns the projection; _postclip_ is a function that takes a [projection stream](https://d3js.org/d3-geo/stream) and returns a clipped stream. If _postclip_ is not specified, returns the current Cartesian clipping function. Post-clipping occurs on the plane, when a projection is bounded to a certain extent such as a rectangle.

## _projection_.clipAngle( _angle_) [​](https://d3js.org/d3-geo/projection\#projection_clipAngle)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · If _angle_ is specified, sets the projection’s clipping circle radius to the specified angle in degrees and returns the projection. If _angle_ is null, switches to [antimeridian cutting](https://observablehq.com/@d3/antimeridian-cutting) rather than small-circle clipping. If _angle_ is not specified, returns the current clip angle which defaults to null. Small-circle clipping is independent of viewport clipping via [_projection_.clipExtent](https://d3js.org/d3-geo/projection#projection_clipExtent). See also [_projection_.preclip](https://d3js.org/d3-geo/projection#projection_preclip), [geoClipAntimeridian](https://d3js.org/d3-geo/projection#geoClipAntimeridian), [geoClipCircle](https://d3js.org/d3-geo/projection#geoClipCircle).

## _projection_.clipExtent( _extent_) [​](https://d3js.org/d3-geo/projection\#projection_clipExtent)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · If _extent_ is specified, sets the projection’s viewport clip extent to the specified bounds in pixels and returns the projection. The _extent_ bounds are specified as an array \[\[ _x₀_, _y₀_\], \[ _x₁_, _y₁_\]\], where _x₀_ is the left-side of the viewport, _y₀_ is the top, _x₁_ is the right and _y₁_ is the bottom. If _extent_ is null, no viewport clipping is performed. If _extent_ is not specified, returns the current viewport clip extent which defaults to null. Viewport clipping is independent of small-circle clipping via [_projection_.clipAngle](https://d3js.org/d3-geo/projection#projection_clipAngle). See also [_projection_.postclip](https://d3js.org/d3-geo/projection#projection_postclip), [geoClipRectangle](https://d3js.org/d3-geo/projection#geoClipRectangle).

## _projection_.scale( _scale_) [​](https://d3js.org/d3-geo/projection\#projection_scale)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · If _scale_ is specified, sets the projection’s scale factor to the specified value and returns the projection. If _scale_ is not specified, returns the current scale factor; the default scale is projection-specific. The scale factor corresponds linearly to the distance between projected points; however, absolute scale factors are not equivalent across projections.

## _projection_.translate( _translate_) [​](https://d3js.org/d3-geo/projection\#projection_translate)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · If _translate_ is specified, sets the projection’s translation offset to the specified two-element array \[ _tx_, _ty_\] and returns the projection. If _translate_ is not specified, returns the current translation offset which defaults to \[480, 250\]. The translation offset determines the pixel coordinates of the projection’s [center](https://d3js.org/d3-geo/projection#projection_center). The default translation offset places ⟨0°,0°⟩ at the center of a 960×500 area.

## _projection_.center( _center_) [​](https://d3js.org/d3-geo/projection\#projection_center)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · If _center_ is specified, sets the projection’s center to the specified _center_, a two-element array of \[ _longitude_, _latitude_\] in degrees and returns the projection. If _center_ is not specified, returns the current center, which defaults to ⟨0°,0°⟩.

## _projection_.angle( _angle_) [​](https://d3js.org/d3-geo/projection\#projection_angle)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · If _angle_ is specified, sets the projection’s post-projection planar rotation angle to the specified _angle_ in degrees and returns the projection. If _angle_ is not specified, returns the projection’s current angle, which defaults to 0°. Note that it may be faster to rotate during rendering (e.g., using [_context_.rotate](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/rotate)) rather than during projection.

## _projection_.reflectX( _reflect_) [​](https://d3js.org/d3-geo/projection\#projection_reflectX)

If _reflect_ is specified, sets whether or not the _x_-dimension is reflected (negated) in the output. If _reflect_ is not specified, returns true if _x_-reflection is enabled, which defaults to false. This can be useful to display sky and astronomical data with the orb seen from below: right ascension (eastern direction) will point to the left when North is pointing up.

## _projection_.reflectY( _reflect_) [​](https://d3js.org/d3-geo/projection\#projection_reflectY)

If _reflect_ is specified, sets whether or not the _y_-dimension is reflected (negated) in the output. If _reflect_ is not specified, returns true if _y_-reflection is enabled, which defaults to false. This is especially useful for transforming from standard [spatial reference systems](https://en.wikipedia.org/wiki/Spatial_reference_system), which treat positive _y_ as pointing up, to display coordinate systems such as Canvas and SVG, which treat positive _y_ as pointing down.

## _projection_.rotate( _angles_) [​](https://d3js.org/d3-geo/projection\#projection_rotate)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · If _angles_ is specified, sets the projection’s [three-axis spherical rotation](https://observablehq.com/@d3/three-axis-rotation) to the specified value, which must be a two- or three-element array of numbers \[ _lambda_, _phi_, _gamma_\] specifying the rotation angles in degrees about [each spherical axis](https://observablehq.com/@d3/three-axis-rotation). (These correspond to [yaw, pitch and roll](https://en.wikipedia.org/wiki/Aircraft_principal_axes).) If the rotation angle _gamma_ is omitted, it defaults to 0. See also [geoRotation](https://d3js.org/d3-geo/math#geoRotation). If _angles_ is not specified, returns the current rotation which defaults to \[0, 0, 0\].

## _projection_.precision( _precision_) [​](https://d3js.org/d3-geo/projection\#projection_precision)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · If _precision_ is specified, sets the threshold for the projection’s [adaptive resampling](https://observablehq.com/@d3/adaptive-sampling) to the specified value in pixels and returns the projection. This value corresponds to the [Douglas–Peucker](https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm) distance. If _precision_ is not specified, returns the projection’s current resampling precision which defaults to √0.5 ≅ 0.70710…

## _projection_.fitExtent( _extent_, _object_) [​](https://d3js.org/d3-geo/projection\#projection_fitExtent)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · Sets the projection’s [scale](https://d3js.org/d3-geo/projection#projection_scale) and [translate](https://d3js.org/d3-geo/projection#projection_translate) to fit the specified GeoJSON _object_ in the center of the given _extent_. The extent is specified as an array \[\[x₀, y₀\], \[x₁, y₁\]\], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. Returns the projection.

For example, to scale and translate the [New Jersey State Plane projection](https://observablehq.com/@d3/new-jersey-state-plane) to fit a GeoJSON object _nj_ in the center of a 960×500 bounding box with 20 pixels of padding on each side:

js

```
var projection = d3.geoTransverseMercator()
    .rotate([74 + 30 / 60, -38 - 50 / 60])
    .fitExtent([[20, 20], [940, 480]], nj);
```

Any [clip extent](https://d3js.org/d3-geo/projection#projection_clipExtent) is ignored when determining the new scale and translate. The [precision](https://d3js.org/d3-geo/projection#projection_precision) used to compute the bounding box of the given _object_ is computed at an effective scale of 150.

## _projection_.fitSize( _size_, _object_) [​](https://d3js.org/d3-geo/projection\#projection_fitSize)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · A convenience method for [_projection_.fitExtent](https://d3js.org/d3-geo/projection#projection_fitExtent) where the top-left corner of the extent is \[0, 0\]. The following two statements are equivalent:

js

```
projection.fitExtent([[0, 0], [width, height]], object);
projection.fitSize([width, height], object);
```

## _projection_.fitWidth( _width_, _object_) [​](https://d3js.org/d3-geo/projection\#projection_fitWidth)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · A convenience method for [_projection_.fitSize](https://d3js.org/d3-geo/projection#projection_fitSize) where the height is automatically chosen from the aspect ratio of _object_ and the given constraint on _width_.

## _projection_.fitHeight( _height_, _object_) [​](https://d3js.org/d3-geo/projection\#projection_fitHeight)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · A convenience method for [_projection_.fitSize](https://d3js.org/d3-geo/projection#projection_fitSize) where the width is automatically chosen from the aspect ratio of _object_ and the given constraint on _height_.

## Raw projections [​](https://d3js.org/d3-geo/projection\#raw-projections)

Raw projections are point transformation functions that are used to implement custom projections; they typically passed to [geoProjection](https://d3js.org/d3-geo/projection#geoProjection) or [geoProjectionMutator](https://d3js.org/d3-geo/projection#geoProjectionMutator). They are exposed here to facilitate the derivation of related projections. Raw projections take spherical coordinates \[ _lambda_, _phi_\] in radians (not degrees!) and return a point \[ _x_, _y_\], typically in the unit square centered around the origin.

### _project_( _lambda_, _phi_) [​](https://d3js.org/d3-geo/projection\#_project)

Projects the specified point \[ _lambda_, _phi_\] in radians, returning a new point \[ _x_, _y_\] in unitless coordinates.

### _project_.invert( _x_, _y_) [​](https://d3js.org/d3-geo/projection\#project_invert)

The inverse of [_project_](https://d3js.org/d3-geo/projection#_project).

## geoProjection( _project_) [​](https://d3js.org/d3-geo/projection\#geoProjection)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · Constructs a new projection from the specified [raw projection](https://d3js.org/d3-geo/projection#raw-projections), _project_. The _project_ function takes the _longitude_ and _latitude_ of a given point in [radians](http://mathworld.wolfram.com/Radian.html), often referred to as _lambda_ (λ) and _phi_ (φ), and returns a two-element array \[ _x_, _y_\] representing its unit projection. The _project_ function does not need to scale or translate the point, as these are applied automatically by [_projection_.scale](https://d3js.org/d3-geo/projection#projection_scale), [_projection_.translate](https://d3js.org/d3-geo/projection#projection_translate), and [_projection_.center](https://d3js.org/d3-geo/projection#projection_center). Likewise, the _project_ function does not need to perform any spherical rotation, as [_projection_.rotate](https://d3js.org/d3-geo/projection#projection_rotate) is applied prior to projection.

For example, a spherical Mercator projection can be implemented as:

js

```
var mercator = d3.geoProjection(function(x, y) {
  return [x, Math.log(Math.tan(Math.PI / 4 + y / 2))];
});
```

If the _project_ function exposes an _invert_ method, the returned projection will also expose [_projection_.invert](https://d3js.org/d3-geo/projection#projection_invert).

## geoProjectionMutator( _factory_) [​](https://d3js.org/d3-geo/projection\#geoProjectionMutator)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/index.js) · Constructs a new projection from the specified [raw projection](https://d3js.org/d3-geo/projection#_project) _factory_ and returns a _mutate_ function to call whenever the raw projection changes. The _factory_ must return a raw projection. The returned _mutate_ function returns the wrapped projection. For example, a conic projection typically has two configurable parallels. A suitable _factory_ function, such as [geoConicEqualAreaRaw](https://d3js.org/d3-geo/conic#geoConicEqualArea), would have the form:

js

```
// y0 and y1 represent two parallels
function conicFactory(phi0, phi1) {
  return function conicRaw(lambda, phi) {
    return […, …];
  };
}
```

Using d3.geoProjectionMutator, you can implement a standard projection that allows the parallels to be changed, reassigning the raw projection used internally by [geoProjection](https://d3js.org/d3-geo/projection#geoProjection):

js

```
function conicCustom() {
  var phi0 = 29.5,
      phi1 = 45.5,
      mutate = d3.geoProjectionMutator(conicFactory),
      projection = mutate(phi0, phi1);

  projection.parallels = function(_) {
    return arguments.length ? mutate(phi0 = +_[0], phi1 = +_[1]) : [phi0, phi1];
  };

  return projection;
}
```

When creating a mutable projection, the _mutate_ function is typically not exposed.

## geoTransform( _methods_) [​](https://d3js.org/d3-geo/projection\#geoTransform)

[Source](https://github.com/d3/d3-geo/blob/main/src/transform.js) · Defines an arbitrary transform using the methods defined on the specified _methods_ object. Any undefined methods will use pass-through methods that propagate inputs to the output stream.

For example, to reflect the _y_-dimension (see also [_projection_.reflectY](https://d3js.org/d3-geo/projection#projection_reflectY)):

js

```
const reflectY = d3.geoTransform({
  point(x, y) {
    this.stream.point(x, -y);
  }
});
```

Or to define an affine matrix transformation:

js

```
function matrix(a, b, c, d, tx, ty) {
  return d3.geoTransform({
    point(x, y) {
      this.stream.point(a * x + b * y + tx, c * x + d * y + ty);
    }
  });
}
```

A transform is a generalized projection; it implements [_projection_.stream](https://d3js.org/d3-geo/projection#projection_stream) and can be passed to [_path_.projection](https://d3js.org/d3-geo/path#path_projection). However, it implements only a subset of the other projection methods, and represent arbitrary geometric transformations rather than projections from spherical to planar coordinates.

## geoIdentity() [​](https://d3js.org/d3-geo/projection\#geoIdentity)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/identity.js) · The identity transform can be used to scale, translate and clip planar geometry. It implements [_projection_.scale](https://d3js.org/d3-geo/projection#projection_scale), [_projection_.translate](https://d3js.org/d3-geo/projection#projection_translate), [_projection_.fitExtent](https://d3js.org/d3-geo/projection#projection_fitExtent), [_projection_.fitSize](https://d3js.org/d3-geo/projection#projection_fitSize), [_projection_.fitWidth](https://d3js.org/d3-geo/projection#projection_fitWidth), [_projection_.fitHeight](https://d3js.org/d3-geo/projection#projection_fitHeight), [_projection_.clipExtent](https://d3js.org/d3-geo/projection#projection_clipExtent), [_projection_.angle](https://d3js.org/d3-geo/projection#projection_angle), [_projection_.reflectX](https://d3js.org/d3-geo/projection#projection_reflectX) and [_projection_.reflectY](https://d3js.org/d3-geo/projection#projection_reflectY).

## geoClipAntimeridian [​](https://d3js.org/d3-geo/projection\#geoClipAntimeridian)

[Source](https://github.com/d3/d3-geo/blob/main/src/clip/antimeridian.js) · A clipping function which transforms a stream such that geometries (lines or polygons) that cross the antimeridian line are cut in two, one on each side. Typically used for pre-clipping.

## geoClipCircle( _angle_) [​](https://d3js.org/d3-geo/projection\#geoClipCircle)

[Source](https://github.com/d3/d3-geo/blob/main/src/clip/circle.js) · Generates a clipping function which transforms a stream such that geometries are bounded by a small circle of radius _angle_ around the projection’s [center](https://d3js.org/d3-geo/projection#projection_center). Typically used for pre-clipping.

## geoClipRectangle( _x0_, _y0_, _x1_, _y1_) [​](https://d3js.org/d3-geo/projection\#geoClipRectangle)

[Source](https://github.com/d3/d3-geo/blob/main/src/clip/rectangle.js) · Generates a clipping function which transforms a stream such that geometries are bounded by a rectangle of coordinates \[\[ _x0_, _y0_\], \[ _x1_, _y1_\]\]. Typically used for post-clipping.

## D3.js Transition Modifications
[Skip to content](https://d3js.org/d3-transition/modifying#VPContent)

On this page

# Modifying elements [​](https://d3js.org/d3-transition/modifying\#modifying-elements)

After selecting elements and creating a transition with [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition), use the transition’s transformation methods to affect document content.

## _transition_.attr( _name_, _value_) [​](https://d3js.org/d3-transition/modifying\#transition_attr)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/attr.js) · For each selected element, assigns the [attribute tween](https://d3js.org/d3-transition/modifying#transition_attrTween) for the attribute with the specified _name_ to the specified target _value_. The starting value of the tween is the attribute’s value when the transition starts. The target _value_ may be specified either as a constant or a function. If a function, it is immediately evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element.

If the target value is null, the attribute is removed when the transition starts. Otherwise, an interpolator is chosen based on the type of the target value, using the following algorithm:

1. If _value_ is a number, use [interpolateNumber](https://d3js.org/d3-interpolate/value#interpolateNumber).
2. If _value_ is a [color](https://d3js.org/d3-color) or a string coercible to a color, use [interpolateRgb](https://d3js.org/d3-interpolate/color#interpolateRgb).
3. Use [interpolateString](https://d3js.org/d3-interpolate/value#interpolateString).

To apply a different interpolator, use [_transition_.attrTween](https://d3js.org/d3-transition/modifying#transition_attrTween).

## _transition_.attrTween( _name_, _factory_) [​](https://d3js.org/d3-transition/modifying\#transition_attrTween)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/attrTween.js) · If _factory_ is specified and not null, assigns the attribute [tween](https://d3js.org/d3-transition/modifying#transition_tween) for the attribute with the specified _name_ to the specified interpolator _factory_. An interpolator factory is a function that returns an [interpolator](https://d3js.org/d3-interpolate); when the transition starts, the _factory_ is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The returned interpolator will then be invoked for each frame of the transition, in order, being passed the [eased](https://d3js.org/d3-transition/timing#transition_ease) time _t_, typically in the range \[0, 1\]. Lastly, the return value of the interpolator will be used to set the attribute value. The interpolator must return a string. (To remove an attribute at the start of a transition, use [_transition_.attr](https://d3js.org/d3-transition/modifying#transition_attr); to remove an attribute at the end of a transition, use [_transition_.on](https://d3js.org/d3-transition/control-flow#transition_on) to listen for the _end_ event.)

If the specified _factory_ is null, removes the previously-assigned attribute tween of the specified _name_, if any. If _factory_ is not specified, returns the current interpolator factory for attribute with the specified _name_, or undefined if no such tween exists.

For example, to interpolate the fill attribute from red to blue:

js

```
transition.attrTween("fill", () => d3.interpolateRgb("red", "blue"));
```

Or to interpolate from the current fill to blue, like [_transition_.attr](https://d3js.org/d3-transition/modifying#transition_attr):

js

```
transition.attrTween("fill", function() {
  return d3.interpolateRgb(this.getAttribute("fill"), "blue");
});
```

Or to apply a custom rainbow interpolator:

js

```
transition.attrTween("fill", () => (t) => `hsl(${t * 360},100%,50%)`);
```

This method is useful to specify a custom interpolator, such as one that understands [SVG paths](https://observablehq.com/@d3/path-tween). A useful technique is _data interpolation_, where [interpolateObject](https://d3js.org/d3-interpolate/value#interpolateObject) is used to interpolate two data values, and the resulting value is then used (say, with a [shape](https://d3js.org/d3-shape)) to compute the new attribute value.

## _transition_.style( _name_, _value_, _priority_) [​](https://d3js.org/d3-transition/modifying\#transition_style)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/style.js) · For each selected element, assigns the [style tween](https://d3js.org/d3-transition/modifying#transition_styleTween) for the style with the specified _name_ to the specified target _value_ with the specified _priority_. The starting value of the tween is the style’s inline value if present, and otherwise its computed value, when the transition starts. The target _value_ may be specified either as a constant or a function. If a function, it is immediately evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element.

If the target value is null, the style is removed when the transition starts. Otherwise, an interpolator is chosen based on the type of the target value, using the following algorithm:

1. If _value_ is a number, use [interpolateNumber](https://d3js.org/d3-interpolate/value#interpolateNumber).
2. If _value_ is a [color](https://d3js.org/d3-color) or a string coercible to a color, use [interpolateRgb](https://d3js.org/d3-interpolate/color#interpolateRgb).
3. Use [interpolateString](https://d3js.org/d3-interpolate/value#interpolateString).

To apply a different interpolator, use [_transition_.styleTween](https://d3js.org/d3-transition/modifying#transition_styleTween).

## _transition_.styleTween( _name_, _factory_, _priority_) [​](https://d3js.org/d3-transition/modifying\#transition_styleTween)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/styleTween.js) · If _factory_ is specified and not null, assigns the style [tween](https://d3js.org/d3-transition/modifying#transition_tween) for the style with the specified _name_ to the specified interpolator _factory_. An interpolator factory is a function that returns an [interpolator](https://d3js.org/d3-interpolate); when the transition starts, the _factory_ is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The returned interpolator will then be invoked for each frame of the transition, in order, being passed the [eased](https://d3js.org/d3-transition/timing#transition_ease) time _t_, typically in the range \[0, 1\]. Lastly, the return value of the interpolator will be used to set the style value with the specified _priority_. The interpolator must return a string. (To remove an style at the start of a transition, use [_transition_.style](https://d3js.org/d3-transition/modifying#transition_style); to remove an style at the end of a transition, use [_transition_.on](https://d3js.org/d3-transition/control-flow#transition_on) to listen for the _end_ event.)

If the specified _factory_ is null, removes the previously-assigned style tween of the specified _name_, if any. If _factory_ is not specified, returns the current interpolator factory for style with the specified _name_, or undefined if no such tween exists.

For example, to interpolate the fill style from red to blue:

js

```
transition.styleTween("fill", () => d3.interpolateRgb("red", "blue"));
```

Or to interpolate from the current fill to blue, like [_transition_.style](https://d3js.org/d3-transition/modifying#transition_style):

js

```
transition.styleTween("fill", function() {
  return d3.interpolateRgb(this.style.fill, "blue");
});
```

Or to apply a custom rainbow interpolator:

js

```
transition.styleTween("fill", () => (t) => `hsl(${t * 360},100%,50%)`);
```

This method is useful to specify a custom interpolator, such as with _data interpolation_, where [interpolateObject](https://d3js.org/d3-interpolate/value#interpolateObject) is used to interpolate two data values, and the resulting value is then used to compute the new style value.

## _transition_.text( _value_) [​](https://d3js.org/d3-transition/modifying\#transition_text)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/text.js) · For each selected element, sets the [text content](http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-textContent) to the specified target _value_ when the transition starts. The _value_ may be specified either as a constant or a function. If a function, it is immediately evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The function’s return value is then used to set each element’s text content. A null value will clear the content.

To interpolate text rather than to set it on start, use [_transition_.textTween](https://d3js.org/d3-transition/modifying#transition_textTween) or append a replacement element and cross-fade opacity. Text is not interpolated by default because it is usually undesirable.

## _transition_.textTween( _factory_) [​](https://d3js.org/d3-transition/modifying\#transition_textTween)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/textTween.js), [Examples](https://observablehq.com/@d3/transition-texttween)

If _factory_ is specified and not null, assigns the text [tween](https://d3js.org/d3-transition/modifying#transition_tween) to the specified interpolator _factory_. An interpolator factory is a function that returns an [interpolator](https://d3js.org/d3-interpolate); when the transition starts, the _factory_ is evaluated for each selected element, in order, being passed the current datum `d` and index `i`, with the `this` context as the current DOM element. The returned interpolator will then be invoked for each frame of the transition, in order, being passed the [eased](https://d3js.org/d3-transition/timing#transition_ease) time _t_, typically in the range \[0, 1\]. Lastly, the return value of the interpolator will be used to set the text. The interpolator must return a string.

For example, to interpolate the text with integers from 0 to 100:

js

```
transition.textTween(() => d3.interpolateRound(0, 100));
```

If the specified _factory_ is null, removes the previously-assigned text tween, if any. If _factory_ is not specified, returns the current interpolator factory for text, or undefined if no such tween exists.

## _transition_.remove() [​](https://d3js.org/d3-transition/modifying\#transition_remove)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/remove.js) · For each selected element, [removes](https://d3js.org/d3-selection/modifying#selection_remove) the element when the transition ends, as long as the element has no other active or pending transitions. If the element has other active or pending transitions, does nothing.

## _transition_.tween(name, value) [​](https://d3js.org/d3-transition/modifying\#transition_tween)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/tween.js) · For each selected element, assigns the tween with the specified _name_ with the specified _value_ function. The _value_ must be specified as a function that returns a function. When the transition starts, the _value_ function is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The returned function is then invoked for each frame of the transition, in order, being passed the [eased](https://d3js.org/d3-transition/timing#transition_ease) time _t_, typically in the range \[0, 1\]. If the specified _value_ is null, removes the previously-assigned tween of the specified _name_, if any.

For example, to interpolate the fill attribute to blue, like [_transition_.attr](https://d3js.org/d3-transition/modifying#transition_attr):

js

```
transition.tween("attr.fill", function() {
  const i = d3.interpolateRgb(this.getAttribute("fill"), "blue");
  return function(t) {
    this.setAttribute("fill", i(t));
  };
});
```

## Sequential Color Schemes
[Skip to content](https://d3js.org/d3-scale-chromatic/sequential#VPContent)

On this page

# Sequential schemes [​](https://d3js.org/d3-scale-chromatic/sequential\#sequential-schemes)

Sequential color schemes are available as continuous interpolators (often used with [d3.scaleSequential](https://d3js.org/d3-scale/sequential)) and as discrete schemes (often used with [d3.scaleOrdinal](https://d3js.org/d3-scale/ordinal)).

Each discrete scheme, such as [d3.schemeBlues](https://d3js.org/d3-scale-chromatic/sequential#schemeBlues), is represented as an array of arrays of hexadecimal color strings. The _k_ th element of this array contains the color scheme of size _k_; for example, `d3.schemeBlues[9]` contains an array of nine strings representing the nine colors of the blue sequential color scheme. Sequential color schemes support a size _k_ ranging from 3 to 9.

To create a sequential discrete nine-color scale using the [Blues](https://d3js.org/d3-scale-chromatic/sequential#schemeBlues) color scheme:

js

```
const color = d3.scaleOrdinal(d3.schemeBlues[9]);
```

To create a sequential continuous color scale using the [Blues](https://d3js.org/d3-scale-chromatic/sequential#interpolateBlues) color scheme:

js

```
const color = d3.scaleSequential(d3.interpolateBlues);
```

## interpolateBlues(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateBlues)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Blues.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “Blues” sequential color scheme represented as an RGB string.

## interpolateGreens(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateGreens)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Greens.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “Greens” sequential color scheme represented as an RGB string.

## interpolateGreys(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateGreys)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Greys.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “Greys” sequential color scheme represented as an RGB string.

## interpolateOranges(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateOranges)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Oranges.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “Oranges” sequential color scheme represented as an RGB string.

## interpolatePurples(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolatePurples)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Purples.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “Purples” sequential color scheme represented as an RGB string.

## interpolateReds(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateReds)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Reds.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “Reds” sequential color scheme represented as an RGB string.

## interpolateTurbo(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateTurbo)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/turbo.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “turbo” color scheme by [Anton Mikhailov](https://ai.googleblog.com/2019/08/turbo-improved-rainbow-colormap-for.html).

## interpolateViridis(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateViridis)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/viridis.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “viridis” perceptually-uniform color scheme designed by [van der Walt, Smith and Firing](https://bids.github.io/colormap/) for matplotlib, represented as an RGB string.

## interpolateInferno(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateInferno)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/viridis.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “inferno” perceptually-uniform color scheme designed by [van der Walt and Smith](https://bids.github.io/colormap/) for matplotlib, represented as an RGB string.

## interpolateMagma(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateMagma)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/viridis.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “magma” perceptually-uniform color scheme designed by [van der Walt and Smith](https://bids.github.io/colormap/) for matplotlib, represented as an RGB string.

## interpolatePlasma(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolatePlasma)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/viridis.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “plasma” perceptually-uniform color scheme designed by [van der Walt and Smith](https://bids.github.io/colormap/) for matplotlib, represented as an RGB string.

## interpolateCividis(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateCividis)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/cividis.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “cividis” color vision deficiency-optimized color scheme designed by [Nuñez, Anderton, and Renslow](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0199239), represented as an RGB string.

## interpolateWarm(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateWarm)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/rainbow.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from a 180° rotation of [Niccoli’s perceptual rainbow](https://mycarta.wordpress.com/2013/02/21/perceptual-rainbow-palette-the-method/), represented as an RGB string.

## interpolateCool(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateCool)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/rainbow.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from [Niccoli’s perceptual rainbow](https://mycarta.wordpress.com/2013/02/21/perceptual-rainbow-palette-the-method/), represented as an RGB string.

## interpolateCubehelixDefault(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateCubehelixDefault)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/cubehelix.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from [Green’s default Cubehelix](http://www.mrao.cam.ac.uk/~dag/CUBEHELIX/) represented as an RGB string.

## interpolateBuGn(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateBuGn)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/BuGn.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “BuGn” sequential color scheme represented as an RGB string.

## interpolateBuPu(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateBuPu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/BuPu.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “BuPu” sequential color scheme represented as an RGB string.

## interpolateGnBu(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateGnBu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/GnBu.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “GnBu” sequential color scheme represented as an RGB string.

## interpolateOrRd(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateOrRd)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/OrRd.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “OrRd” sequential color scheme represented as an RGB string.

## interpolatePuBuGn(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolatePuBuGn)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/PuBuGn.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “PuBuGn” sequential color scheme represented as an RGB string.

## interpolatePuBu(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolatePuBu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/PuBu.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “PuBu” sequential color scheme represented as an RGB string.

## interpolatePuRd(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolatePuRd)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/PuRd.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “PuRd” sequential color scheme represented as an RGB string.

## interpolateRdPu(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateRdPu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/RdPu.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “RdPu” sequential color scheme represented as an RGB string.

## interpolateYlGnBu(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateYlGnBu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/YlGnBu.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “YlGnBu” sequential color scheme represented as an RGB string.

## interpolateYlGn(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateYlGn)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/YlGn.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “YlGn” sequential color scheme represented as an RGB string.

## interpolateYlOrBr(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateYlOrBr)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/YlOrBr.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “YlOrBr” sequential color scheme represented as an RGB string.

## interpolateYlOrRd(t) [​](https://d3js.org/d3-scale-chromatic/sequential\#interpolateYlOrRd)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/YlOrRd.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “YlOrRd” sequential color scheme represented as an RGB string.

## schemeBlues\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeBlues)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Blues.js) · The “Blues” discrete sequential color scheme of size _k_ in 3–9.

## schemeGreens\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeGreens)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Greens.js) · The “Greens” discrete sequential color scheme of size _k_ in 3–9.

## schemeGreys\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeGreys)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Greys.js) · The “Greys” discrete sequential color scheme of size _k_ in 3–9.

## schemeOranges\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeOranges)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Oranges.js) · The “Oranges” discrete sequential color scheme of size _k_ in 3–9.

## schemePurples\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemePurples)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Purples.js) · The “Purples” discrete sequential color scheme of size _k_ in 3–9.

## schemeReds\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeReds)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-single/Reds.js) · The “Reds” discrete sequential color scheme of size _k_ in 3–9.

## schemeBuGn\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeBuGn)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/BuGn.js) · The “BuGn” discrete sequential color scheme of size _k_ in 3–9.

## schemeBuPu\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeBuPu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/BuPu.js) · The “BuPu” discrete sequential color scheme of size _k_ in 3–9.

## schemeGnBu\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeGnBu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/GnBu.js) · The “GnBu” discrete sequential color scheme of size _k_ in 3–9.

## schemeOrRd\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeOrRd)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/OrRd.js) · The “OrRd” discrete sequential color scheme of size _k_ in 3–9.

## schemePuBuGn\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemePuBuGn)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/PuBuGn.js) · The “PuBuGn” discrete sequential color scheme of size _k_ in 3–9.

## schemePuBu\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemePuBu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/PuBu.js) · The “PuBu” discrete sequential color scheme of size _k_ in 3–9.

## schemePuRd\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemePuRd)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/PuRd.js) · The “PuRd” discrete sequential color scheme of size _k_ in 3–9.

## schemeRdPu\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeRdPu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/RdPu.js) · The “RdPu” discrete sequential color scheme of size _k_ in 3–9.

## schemeYlGnBu\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeYlGnBu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/YlGnBu.js) · The “YlGnBu” discrete sequential color scheme of size _k_ in 3–9.

## schemeYlGn\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeYlGn)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/YlGn.js) · The “YlGn” discrete sequential color scheme of size _k_ in 3–9.

## schemeYlOrBr\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeYlOrBr)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/YlOrBr.js) · The “YlOrBr” discrete sequential color scheme of size _k_ in 3–9.

## schemeYlOrRd\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/sequential\#schemeYlOrRd)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/sequential-multi/YlOrRd.js) · The “YlOrRd” discrete sequential color scheme of size _k_ in 3–9.

## D3.js Geo Streams
[Skip to content](https://d3js.org/d3-geo/stream#VPContent)

On this page

# Streams [​](https://d3js.org/d3-geo/stream\#streams)

Rather than materializing intermediate representations, streams transform geometry through function calls to minimize overhead. Streams must implement several methods to receive input geometry. Streams are inherently stateful; the meaning of a [point](https://d3js.org/d3-geo/stream#stream_point) depends on whether the point is inside of a [line](https://d3js.org/d3-geo/stream#stream_lineStart), and likewise a line is distinguished from a ring by a [polygon](https://d3js.org/d3-geo/stream#stream_polygonStart). Despite the name “stream”, these method calls are currently synchronous.

## geoStream( _object_, _stream_) [​](https://d3js.org/d3-geo/stream\#geoStream)

[Source](https://github.com/d3/d3-geo/blob/main/src/stream.js) · Streams the specified [GeoJSON](http://geojson.org/) _object_ to the specified [projection _stream_](https://d3js.org/d3-geo/stream#streams). While both features and geometry objects are supported as input, the stream interface only describes the geometry, and thus additional feature properties are not visible to streams.

## _stream_.point( _x_, _y_, _z_) [​](https://d3js.org/d3-geo/stream\#stream_point)

Indicates a point with the specified coordinates _x_ and _y_ (and optionally _z_). The coordinate system is unspecified and implementation-dependent; for example, [projection streams](https://d3js.org/d3-geo/projection#projection_stream) require spherical coordinates in degrees as input. Outside the context of a polygon or line, a point indicates a point geometry object ( [Point](http://www.geojson.org/geojson-spec.html#stream_point) or [MultiPoint](http://www.geojson.org/geojson-spec.html#multipoint)). Within a line or polygon ring, the point indicates a control point.

## _stream_.lineStart() [​](https://d3js.org/d3-geo/stream\#stream_lineStart)

Indicates the start of a line or ring. Within a polygon, indicates the start of a ring. The first ring of a polygon is the exterior ring, and is typically clockwise. Any subsequent rings indicate holes in the polygon, and are typically counterclockwise.

## _stream_.lineEnd() [​](https://d3js.org/d3-geo/stream\#stream_lineEnd)

Indicates the end of a line or ring. Within a polygon, indicates the end of a ring. Unlike GeoJSON, the redundant closing coordinate of a ring is _not_ indicated via [point](https://d3js.org/d3-geo/stream#stream_point), and instead is implied via lineEnd within a polygon. Thus, the given polygon input:

json

```
{
  "type": "Polygon",
  "coordinates": [[[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]]
}
```

Will produce the following series of method calls on the stream:

js

```
stream.polygonStart();
stream.lineStart();
stream.point(0, 0);
stream.point(0, 1);
stream.point(1, 1);
stream.point(1, 0);
stream.lineEnd();
stream.polygonEnd();
```

## _stream_.polygonStart() [​](https://d3js.org/d3-geo/stream\#stream_polygonStart)

Indicates the start of a polygon. The first line of a polygon indicates the exterior ring, and any subsequent lines indicate interior holes.

## _stream_.polygonEnd() [​](https://d3js.org/d3-geo/stream\#stream_polygonEnd)

Indicates the end of a polygon.

## _stream_.sphere() [​](https://d3js.org/d3-geo/stream\#stream_sphere)

Indicates the sphere (the globe; the unit sphere centered at ⟨0,0,0⟩).

## Bisection in Arrays
[Skip to content](https://d3js.org/d3-array/bisect#VPContent)

On this page

# Bisecting data [​](https://d3js.org/d3-array/bisect\#bisecting-data)

Bisection, or binary search, quickly finds a given value in a sorted array. It is often used to find the position at which to insert a new value into an array while maintaining sorted order.

## bisector( _accessor_) [​](https://d3js.org/d3-array/bisect\#bisector)

[Examples](https://observablehq.com/@d3/d3-bisect) · [Source](https://github.com/d3/d3-array/blob/main/src/bisector.js) · Returns a new bisector using the specified _accessor_ function.

js

```
const bisector = d3.bisector((d) => d.Date);
```

If the given _accessor_ takes two arguments, it is interpreted as a comparator function for comparing an element _d_ in the data with a search value _x_. Use a comparator rather than an accessor if you want values to be sorted in an order different than natural order, such as in descending rather than ascending order. The above is equivalent to:

js

```
const bisector = d3.bisector((d, x) => d.Date - x);
```

The bisector can be used to bisect sorted arrays of objects (in contrast to [bisect](https://d3js.org/d3-array/bisect#bisect), which is for bisecting primitives).

## _bisector_.right( _array_, _x_, _lo_, _hi_) [​](https://d3js.org/d3-array/bisect\#bisector_right)

js

```
d3.bisector((d) => d.Date).right(aapl, new Date("2014-01-02")) // 163
```

Like [bisectRight](https://d3js.org/d3-array/bisect#bisectRight), but using this bisector’s accessor. The code above finds the index of the row immediately following Jan. 2, 2014 in the [_aapl_ sample dataset](https://observablehq.com/@observablehq/sample-datasets#aapl).

## _bisector_.left( _array_, _x_, _lo_, _hi_) [​](https://d3js.org/d3-array/bisect\#bisector_left)

js

```
d3.bisector((d) => d.Date).left(aapl, new Date("2014-01-02")) // 162
```

Like [bisectLeft](https://d3js.org/d3-array/bisect#bisectLeft), but using this bisector’s accessor. The code above finds the index of the row for Jan. 2, 2014 in the [_aapl_ sample dataset](https://observablehq.com/@observablehq/sample-datasets#aapl).

## _bisector_.center( _array_, _x_, _lo_, _hi_) [​](https://d3js.org/d3-array/bisect\#bisector_center)

js

```
d3.bisector((d) => d.Date).center(aapl, new Date("2013-12-31")) // 161
```

Returns the index of the closest value to _x_ in the given sorted _array_. This expects that the bisector’s accessor returns a quantitative value, or that the bisector’s comparator returns a signed distance; otherwise, this method is equivalent to [_bisector_.left](https://d3js.org/d3-array/bisect#bisector_left). The arguments _lo_ (inclusive) and _hi_ (exclusive) may be used to specify a subset of the array which should be considered; by default the entire array is used.

## bisect( _array_, _x_, _lo_, _hi_) [​](https://d3js.org/d3-array/bisect\#bisect)

js

```
d3.bisect(aapl.map((d) => d.Date), new Date("2014-01-02")) // 163
```

Alias for [bisectRight](https://d3js.org/d3-array/bisect#bisectRight).

## bisectRight( _array_, _x_, _lo_, _hi_) [​](https://d3js.org/d3-array/bisect\#bisectRight)

js

```
d3.bisectRight(aapl.map((d) => d.Date), new Date("2014-01-02")) // 163
```

Like [bisectLeft](https://d3js.org/d3-array/bisect#bisectLeft), but returns an insertion point which comes after (to the right of) any existing entries equivalent to _x_ in _array_. The returned insertion point _i_ partitions the _array_ into two halves so that all _v_ <= _x_ for _v_ in _array_.slice( _lo_, _i_) for the left side and all _v_ \> _x_ for _v_ in _array_.slice( _i_, _hi_) for the right side. See also [_bisector_.right](https://d3js.org/d3-array/bisect#bisector_right).

## bisectLeft( _array_, _x_, _lo_, _hi_) [​](https://d3js.org/d3-array/bisect\#bisectLeft)

js

```
d3.bisectLeft(aapl.map((d) => d.Date), new Date("2014-01-02")) // 162
```

Returns the insertion point for _x_ in _array_ to maintain sorted order. The arguments _lo_ and _hi_ may be used to specify a subset of the array which should be considered; by default the entire array is used. If _x_ is already present in _array_, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first argument to [_array_.splice](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) assuming that _array_ is already sorted. The returned insertion point _i_ partitions the _array_ into two halves so that all _v_ < _x_ for _v_ in _array_.slice( _lo_, _i_) for the left side and all _v_ >= _x_ for _v_ in _array_.slice( _i_, _hi_) for the right side. See also [_bisector_.left](https://d3js.org/d3-array/bisect#bisector_left).

## bisectCenter( _array_, _x_, _lo_, _hi_) [​](https://d3js.org/d3-array/bisect\#bisectCenter)

js

```
d3.bisectCenter(aapl.map((d) => d.Date), new Date("2013-12-31")) // 161
```

Returns the index of the value closest to _x_ in the given _array_ of numbers. The arguments _lo_ (inclusive) and _hi_ (exclusive) may be used to specify a subset of the array which should be considered; by default the entire array is used. See also [_bisector_.center](https://d3js.org/d3-array/bisect#bisector_center).

## Spherical Geometry Utilities
[Skip to content](https://d3js.org/d3-geo/math#VPContent)

On this page

# Spherical math [​](https://d3js.org/d3-geo/math\#spherical-math)

Low-level utilities for spherical geometry.

## geoArea( _object_) [​](https://d3js.org/d3-geo/math\#geoArea)

[Source](https://github.com/d3/d3-geo/blob/main/src/area.js) · Returns the spherical area of the specified GeoJSON _object_ in [steradians](https://en.wikipedia.org/wiki/Steradian). This is the spherical equivalent of [_path_.area](https://d3js.org/d3-geo/path#path_area).

## geoBounds( _object_) [​](https://d3js.org/d3-geo/math\#geoBounds)

[Source](https://github.com/d3/d3-geo/blob/main/src/bounds.js) · Returns the [spherical bounding box](https://www.jasondavies.com/maps/bounds/) for the specified GeoJSON _object_. The bounding box is represented by a two-dimensional array: \[\[ _left_, _bottom_\], \[ _right_, _top_\]\], where _left_ is the minimum longitude, _bottom_ is the minimum latitude, _right_ is maximum longitude, and _top_ is the maximum latitude. All coordinates are given in degrees. (Note that in projected planar coordinates, the minimum latitude is typically the maximum _y_-value, and the maximum latitude is typically the minimum _y_-value.) This is the spherical equivalent of [_path_.bounds](https://d3js.org/d3-geo/path#path_bounds).

## geoCentroid( _object_) [​](https://d3js.org/d3-geo/math\#geoCentroid)

[Source](https://github.com/d3/d3-geo/blob/main/src/centroid.js) · Returns the spherical centroid of the specified GeoJSON _object_. This is the spherical equivalent of [_path_.centroid](https://d3js.org/d3-geo/path#path_centroid).

## geoDistance( _a_, _b_) [​](https://d3js.org/d3-geo/math\#geoDistance)

[Source](https://github.com/d3/d3-geo/blob/main/src/distance.js) · Returns the great-arc distance in [radians](http://mathworld.wolfram.com/Radian.html) between the two points _a_ and _b_. Each point must be specified as a two-element array \[ _longitude_, _latitude_\] in degrees. This is the spherical equivalent of [_path_.measure](https://d3js.org/d3-geo/path#path_measure) given a LineString of two points.

## geoLength( _object_) [​](https://d3js.org/d3-geo/math\#geoLength)

[Source](https://github.com/d3/d3-geo/blob/main/src/length.js) · Returns the great-arc length of the specified GeoJSON _object_ in [radians](http://mathworld.wolfram.com/Radian.html). For polygons, returns the perimeter of the exterior ring plus that of any interior rings. This is the spherical equivalent of [_path_.measure](https://d3js.org/d3-geo/path#path_measure).

## geoInterpolate( _a_, _b_) [​](https://d3js.org/d3-geo/math\#geoInterpolate)

[Source](https://github.com/d3/d3-geo/blob/main/src/interpolate.js) · Returns an interpolator function given two points _a_ and _b_. Each point must be specified as a two-element array \[ _longitude_, _latitude_\] in degrees. The returned interpolator function takes a single argument _t_, where _t_ is a number ranging from 0 to 1; a value of 0 returns the point _a_, while a value of 1 returns the point _b_. Intermediate values interpolate from _a_ to _b_ along the great arc that passes through both _a_ and _b_. If _a_ and _b_ are antipodes, an arbitrary great arc is chosen.

## geoContains( _object_, _point_) [​](https://d3js.org/d3-geo/math\#geoContains)

[Source](https://github.com/d3/d3-geo/blob/main/src/contains.js) · Returns true if and only if the specified GeoJSON _object_ contains the specified _point_, or false if the _object_ does not contain the _point_. The point must be specified as a two-element array \[ _longitude_, _latitude_\] in degrees. For Point and MultiPoint geometries, an exact test is used; for a Sphere, true is always returned; for other geometries, an epsilon threshold is applied.

## geoRotation( _angles_) [​](https://d3js.org/d3-geo/math\#geoRotation)

[Source](https://github.com/d3/d3-geo/blob/main/src/rotation.js) · Returns a [rotation function](https://d3js.org/d3-geo/math#_rotation) for the given _angles_, which must be a two- or three-element array of numbers \[ _lambda_, _phi_, _gamma_\] specifying the rotation angles in degrees about [each spherical axis](https://observablehq.com/@d3/three-axis-rotation). (These correspond to [yaw, pitch and roll](https://en.wikipedia.org/wiki/Aircraft_principal_axes).) If the rotation angle _gamma_ is omitted, it defaults to 0. See also [_projection_.rotate](https://d3js.org/d3-geo/projection#projection_rotate).

### _rotation_( _point_) [​](https://d3js.org/d3-geo/math\#_rotation)

[Source](https://github.com/d3/d3-geo/blob/main/src/rotation.js) · Returns a new array \[ _longitude_, _latitude_\] in degrees representing the rotated point of the given _point_. The point must be specified as a two-element array \[ _longitude_, _latitude_\] in degrees.

### _rotation_.invert( _point_) [​](https://d3js.org/d3-geo/math\#rotation_invert)

[Source](https://github.com/d3/d3-geo/blob/main/src/rotation.js) · Returns a new array \[ _longitude_, _latitude_\] in degrees representing the point of the given rotated _point_; the inverse of [_rotation_](https://d3js.org/d3-geo/math#_rotation). The point must be specified as a two-element array \[ _longitude_, _latitude_\] in degrees.

## Data Binning with D3.js
[Skip to content](https://d3js.org/d3-array/bin#VPContent)

On this page

# Binning data [​](https://d3js.org/d3-array/bin\#binning-data)

Bin quantitative values into consecutive, non-overlapping intervals, as in histograms. (See also Observable Plot’s [bin transform](https://observablehq.com/plot/transforms/bin).)

## bin() [​](https://d3js.org/d3-array/bin\#bin)

js

```
const bin = d3.bin().value((d) => d.culmen_length_mm);
```

[Examples](https://observablehq.com/@d3/d3-bin) · [Source](https://github.com/d3/d3-array/blob/main/src/bin.js) · Constructs a new bin generator with the default settings. The returned bin generator supports method chaining, so this constructor is typically chained with [_bin_.value](https://d3js.org/d3-array/bin#bin_value) to assign a value accessor. The returned generator is also a function; [pass it data](https://d3js.org/d3-array/bin#_bin) to bin.

## _bin_( _data_) [​](https://d3js.org/d3-array/bin\#_bin)

js

```
const bins = d3.bin().value((d) => d.culmen_length_mm)(penguins);
```

Bins the given iterable of _data_ samples. Returns an array of bins, where each bin is an array containing the associated elements from the input _data_. Thus, the `length` of the bin is the number of elements in that bin. Each bin has two additional attributes:

- `x0` \- the lower bound of the bin (inclusive).
- `x1` \- the upper bound of the bin (exclusive, except for the last bin).

Any null or non-comparable values in the given _data_, or those outside the [domain](https://d3js.org/d3-array/bin#bin_domain), are ignored.

## _bin_.value( _value_) [​](https://d3js.org/d3-array/bin\#bin_value)

js

```
const bin = d3.bin().value((d) => d.culmen_length_mm);
```

If _value_ is specified, sets the value accessor to the specified function or constant and returns this bin generator.

js

```
bin.value() // (d) => d.culmen_length_mm
```

If _value_ is not specified, returns the current value accessor, which defaults to the identity function.

When bins are [generated](https://d3js.org/d3-array/bin#_bin), the value accessor will be invoked for each element in the input data array, being passed the element `d`, the index `i`, and the array `data` as three arguments. The default value accessor assumes that the input data are orderable (comparable), such as numbers or dates. If your data are not, then you should specify an accessor that returns the corresponding orderable value for a given datum.

This is similar to mapping your data to values before invoking the bin generator, but has the benefit that the input data remains associated with the returned bins, thereby making it easier to access other fields of the data.

## _bin_.domain( _domain_) [​](https://d3js.org/d3-array/bin\#bin_domain)

js

```
const bin = d3.bin().domain([0, 1]);
```

If _domain_ is specified, sets the domain accessor to the specified function or array and returns this bin generator.

js

```
bin.domain() // [0, 1]
```

If _domain_ is not specified, returns the current domain accessor, which defaults to [extent](https://d3js.org/d3-array/summarize#extent). The bin domain is defined as an array \[ _min_, _max_\], where _min_ is the minimum observable value and _max_ is the maximum observable value; both values are inclusive. Any value outside of this domain will be ignored when the bins are [generated](https://d3js.org/d3-array/bin#_bin).

For example, to use a bin generator with a [linear scale](https://d3js.org/d3-scale/linear) `x`, you might say:

js

```
const bin = d3.bin().domain(x.domain()).thresholds(x.ticks(20));
```

You can then compute the bins from an array of numbers like so:

js

```
const bins = bin(numbers);
```

If the default [extent](https://d3js.org/d3-array/summarize#extent) domain is used and the [thresholds](https://d3js.org/d3-array/bin#bin_thresholds) are specified as a count (rather than explicit values), then the computed domain will be [niced](https://d3js.org/d3-array/ticks#nice) such that all bins are uniform width.

Note that the domain accessor is invoked on the materialized array of [values](https://d3js.org/d3-array/bin#bin_value), not on the input data array.

## _bin_.thresholds( _thresholds_) [​](https://d3js.org/d3-array/bin\#bin_thresholds)

js

```
const bin = d3.bin().thresholds(20);
```

If _thresholds_ is specified as a number, then the [domain](https://d3js.org/d3-array/bin#bin_domain) will be uniformly divided into approximately that many bins; see [ticks](https://d3js.org/d3-array/ticks).

js

```
const bin = d3.bin().thresholds([0.25, 0.5, 0.75]);
```

If _thresholds_ is specified as an array, sets the thresholds to the specified values and returns this bin generator. Thresholds are defined as an array of values \[ _x0_, _x1_, …\]. Any value less than _x0_ will be placed in the first bin; any value greater than or equal to _x0_ but less than _x1_ will be placed in the second bin; and so on. Thus, the [generated bins](https://d3js.org/d3-array/bin#_bin) will have _thresholds_.length + 1 bins. Any threshold values outside the [domain](https://d3js.org/d3-array/bin#bin_domain) are ignored. The first _bin_.x0 is always equal to the minimum domain value, and the last _bin_.x1 is always equal to the maximum domain value.

js

```
const bin = d3.bin().thresholds((values) => [d3.median(values)]);
```

If _thresholds_ is specified as a function, the function will be passed three arguments: the array of input [_values_](https://d3js.org/d3-array/bin#bin_value) derived from the data, and the [domain](https://d3js.org/d3-array/bin#bin_domain) represented as _min_ and _max_. The function may then return either the array of numeric thresholds or the count of bins; in the latter case the domain is divided uniformly into approximately _count_ bins; see [ticks](https://d3js.org/d3-array/ticks#ticks). For instance, you might want to use time ticks when binning time-series data; see [example](https://observablehq.com/@d3/d3-bin-time-thresholds).

js

```
bin.thresholds() // () => [0, 0.5, 1]
```

If _thresholds_ is not specified, returns the current threshold generator, which by default implements [Sturges’ formula](https://d3js.org/d3-array/bin#thresholdSturges). (Thus by default, the values to be binned must be numbers!)

## thresholdFreedmanDiaconis( _values_, _min_, _max_) [​](https://d3js.org/d3-array/bin\#thresholdFreedmanDiaconis)

js

```
const bin = d3.bin().thresholds(d3.thresholdFreedmanDiaconis);
```

[Source](https://github.com/d3/d3-array/blob/main/src/threshold/freedmanDiaconis.js) · Returns the number of bins according to the [Freedman–Diaconis rule](https://en.wikipedia.org/wiki/Histogram#Mathematical_definition); the input _values_ must be numbers.

## thresholdScott( _values_, _min_, _max_) [​](https://d3js.org/d3-array/bin\#thresholdScott)

js

```
const bin = d3.bin().thresholds(d3.thresholdScott);
```

[Source](https://github.com/d3/d3-array/blob/main/src/threshold/scott.js) · Returns the number of bins according to [Scott’s normal reference rule](https://en.wikipedia.org/wiki/Histogram#Mathematical_definition); the input _values_ must be numbers.

## thresholdSturges( _values_, _min_, _max_) [​](https://d3js.org/d3-array/bin\#thresholdSturges)

js

```
const bin = d3.bin().thresholds(d3.thresholdSturges);
```

[Source](https://github.com/d3/d3-array/blob/main/src/threshold/sturges.js) · Returns the number of bins according to [Sturges’ formula](https://en.wikipedia.org/wiki/Histogram#Mathematical_definition); the input _values_ must be numbers.

## D3.js Element Modifications
[Skip to content](https://d3js.org/d3-selection/modifying#VPContent)

On this page

# Modifying elements [​](https://d3js.org/d3-selection/modifying\#modifying-elements)

After selecting elements, use the selection to modify the elements. For example, to set the class and color style of all paragraph elements in the current document:

js

```
d3.selectAll("p")
    .attr("class", "graf")
    .style("color", "red");
```

Selection methods typically return the current selection, or a new selection, allowing the concise application of multiple operations on a given selection via method chaining. The above is equivalent to:

js

```
const p = d3.selectAll("p");
p.attr("class", "graf");
p.style("color", "red");
```

Selections are immutable. All selection methods that affect which elements are selected (or their order) return a new selection rather than modifying the current selection. However, note that elements are necessarily mutable, as selections drive transformations of the document!

## _selection_.attr( _name_, _value_) [​](https://d3js.org/d3-selection/modifying\#selection_attr)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/attr.js) · If a _value_ is specified, sets the attribute with the specified _name_ to the specified value on the selected elements and returns this selection.

js

```
selection.attr("color", "red")
```

If the _value_ is a constant, all elements are given the same attribute value; otherwise, if the _value_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). The function’s return value is then used to set each element’s attribute. A null value will remove the specified attribute.

js

```
selection.attr("color") // "red"
```

If a _value_ is not specified, returns the current value of the specified attribute for the first (non-null) element in the selection. This is generally useful only if you know that the selection contains exactly one element.

The specified _name_ may have a namespace prefix, such as `xlink:href` to specify the `href` attribute in the XLink namespace. See [namespaces](https://d3js.org/d3-selection/namespaces#namespaces) for the map of supported namespaces; additional namespaces can be registered by adding to the map.

## _selection_.classed( _names_, _value_) [​](https://d3js.org/d3-selection/modifying\#selection_classed)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/classed.js) · If a _value_ is specified, assigns or unassigns the specified CSS class _names_ on the selected elements by setting the `class` attribute or modifying the `classList` property and returns this selection.

js

```
selection.classed("foo", true)
```

The specified _names_ is a string of space-separated class names. For example, to assign the classes `foo` and `bar` to the selected elements:

js

```
selection.classed("foo bar", true)
```

If the _value_ is truthy, then all elements are assigned the specified classes; otherwise, the classes are unassigned.

js

```
selection.classed("foo", () => Math.random() > 0.5)
```

If the _value_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). The function’s return value is then used to assign or unassign classes on each element.

js

```
selection.classed("foo") // true, perhaps
```

If a _value_ is not specified, returns true if and only if the first (non-null) selected element has the specified _classes_. This is generally useful only if you know the selection contains exactly one element.

## _selection_.style( _name_, _value_, _priority_) [​](https://d3js.org/d3-selection/modifying\#selection_style)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/style.js) · If a _value_ is specified, sets the style property with the specified _name_ to the specified value on the selected elements and returns this selection.

js

```
selection.style("color", "red")
```

If the _value_ is a constant, then all elements are given the same style property value; otherwise, if the _value_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). The function’s return value is then used to set each element’s style property. A null value will remove the style property. An optional _priority_ may also be specified, either as null or the string `important` (without the exclamation point).

js

```
selection.style("color") // "red"
```

If a _value_ is not specified, returns the current value of the specified style property for the first (non-null) element in the selection. The current value is defined as the element’s inline value, if present, and otherwise its [computed value](https://developer.mozilla.org/en-US/docs/Web/CSS/computed_value). Accessing the current style value is generally useful only if you know the selection contains exactly one element.

CAUTION

Unlike many SVG attributes, CSS styles typically have associated units. For example, `3px` is a valid stroke-width property value, while `3` is not. Some browsers implicitly assign the `px` (pixel) unit to numeric values, but not all browsers do: IE, for example, throws an “invalid arguments” error!

## _selection_.property( _name_, _value_) [​](https://d3js.org/d3-selection/modifying\#selection_property)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/property.js) · Some HTML elements have special properties that are not addressable using attributes or styles, such as a form field’s text `value` and a checkbox’s `checked` boolean. Use this method to get or set these properties.

js

```
selection.property("checked", true)
```

If a _value_ is specified, sets the property with the specified _name_ to the specified value on selected elements. If the _value_ is a constant, then all elements are given the same property value; otherwise, if the _value_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). The function’s return value is then used to set each element’s property. A null value will delete the specified property.

js

```
selection.property("checked") // true, perhaps
```

If a _value_ is not specified, returns the value of the specified property for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element.

## _selection_.text( _value_) [​](https://d3js.org/d3-selection/modifying\#selection_text)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/text.js) · If a _value_ is specified, sets the [text content](http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-textContent) to the specified value on all selected elements, replacing any existing child elements.

js

```
selection.text("Hello, world!")
```

If the _value_ is a constant, then all elements are given the same text content; otherwise, if the _value_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). The function’s return value is then used to set each element’s text content. A null value will clear the content.

js

```
selection.text() // "Hello, world!"
```

If a _value_ is not specified, returns the text content for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element.

## _selection_.html( _value_) [​](https://d3js.org/d3-selection/modifying\#selection_html)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/html.js) · If a _value_ is specified, sets the [inner HTML](http://dev.w3.org/html5/spec-LC/apis-in-html-documents.html#innerhtml) to the specified value on all selected elements, replacing any existing child elements.

js

```
selection.html("Hello, <i>world</i>!")
```

If the _value_ is a constant, then all elements are given the same inner HTML; otherwise, if the _value_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). The function’s return value is then used to set each element’s inner HTML. A null value will clear the content.

js

```
selection.html() // "Hello, <i>world</i>!"
```

If a _value_ is not specified, returns the inner HTML for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element.

Use [_selection_.append](https://d3js.org/d3-selection/modifying#selection_append) or [_selection_.insert](https://d3js.org/d3-selection/modifying#selection_insert) instead to create data-driven content; this method is intended for when you want a little bit of HTML, say for rich formatting. Also, _selection_.html is only supported on HTML elements. SVG elements and other non-HTML elements do not support the innerHTML property, and thus are incompatible with _selection_.html. Consider using [XMLSerializer](https://developer.mozilla.org/en-US/docs/XMLSerializer) to convert a DOM subtree to text. See also the [innersvg polyfill](https://code.google.com/p/innersvg/), which provides a shim to support the innerHTML property on SVG elements.

## _selection_.append( _type_) [​](https://d3js.org/d3-selection/modifying\#selection_append)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/append.js) · If the specified _type_ is a string, appends a new element of this type (tag name) as the last child of each selected element, or before the next following sibling in the update selection if this is an [enter selection](https://d3js.org/d3-selection/joining#selection_enter). The latter behavior for enter selections allows you to insert elements into the DOM in an order consistent with the new bound data; however, note that [_selection_.order](https://d3js.org/d3-selection/modifying#selection_order) may still be required if updating elements change order ( _i.e._, if the order of new data is inconsistent with old data).

If the specified _type_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). This function should return an element to be appended. (The function typically creates a new element, but it may instead return an existing element.) For example, to append a paragraph to each DIV element:

js

```
d3.selectAll("div").append("p");
```

This is equivalent to:

js

```
d3.selectAll("div").append(() => document.createElement("p"));
```

Which is equivalent to:

js

```
d3.selectAll("div").select(function() {
  return this.appendChild(document.createElement("p"));
});
```

In both cases, this method returns a new selection containing the appended elements. Each new element inherits the data of the current elements, if any, in the same manner as [_selection_.select](https://d3js.org/d3-selection/selecting#selection_select).

The specified _name_ may have a namespace prefix, such as `svg:text` to specify a `text` attribute in the SVG namespace. See [namespaces](https://d3js.org/d3-selection/namespaces#namespaces) for the map of supported namespaces; additional namespaces can be registered by adding to the map. If no namespace is specified, the namespace will be inherited from the parent element; or, if the name is one of the known prefixes, the corresponding namespace will be used (for example, `svg` implies `svg:svg`).

## _selection_.insert( _type_, _before_) [​](https://d3js.org/d3-selection/modifying\#selection_insert)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/insert.js) · If the specified _type_ is a string, inserts a new element of this type (tag name) before the first element matching the specified _before_ selector for each selected element. For example, a _before_ selector `:first-child` will prepend nodes before the first child. If _before_ is not specified, it defaults to null. (To append elements in an order consistent with [bound data](https://d3js.org/d3-selection/joining), use [_selection_.append](https://d3js.org/d3-selection/modifying#selection_append).)

Both _type_ and _before_ may instead be specified as functions which are evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). The _type_ function should return an element to be inserted; the _before_ function should return the child element before which the element should be inserted. For example, to append a paragraph to each DIV element:

js

```
d3.selectAll("div").insert("p");
```

This is equivalent to:

js

```
d3.selectAll("div").insert(() => document.createElement("p"));
```

Which is equivalent to:

js

```
d3.selectAll("div").select(function() {
  return this.insertBefore(document.createElement("p"), null);
});
```

In both cases, this method returns a new selection containing the appended elements. Each new element inherits the data of the current elements, if any, in the same manner as [_selection_.select](https://d3js.org/d3-selection/selecting#selection_select).

The specified _name_ may have a namespace prefix, such as `svg:text` to specify a `text` attribute in the SVG namespace. See [namespaces](https://d3js.org/d3-selection/namespaces#namespaces) for the map of supported namespaces; additional namespaces can be registered by adding to the map. If no namespace is specified, the namespace will be inherited from the parent element; or, if the name is one of the known prefixes, the corresponding namespace will be used (for example, `svg` implies `svg:svg`).

## _selection_.remove() [​](https://d3js.org/d3-selection/modifying\#selection_remove)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/remove.js) · Removes the selected elements from the document. Returns this selection (the removed elements) which are now detached from the DOM. There is not currently a dedicated API to add removed elements back to the document; however, you can pass a function to [_selection_.append](https://d3js.org/d3-selection/modifying#selection_append) or [_selection_.insert](https://d3js.org/d3-selection/modifying#selection_insert) to re-add elements.

## _selection_.clone( _deep_) [​](https://d3js.org/d3-selection/modifying\#selection_clone)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/clone.js) · Inserts clones of the selected elements immediately following the selected elements and returns a selection of the newly added clones. If _deep_ is truthy, the descendant nodes of the selected elements will be cloned as well. Otherwise, only the elements themselves will be cloned. Equivalent to:

js

```
selection.select(function() {
  return this.parentNode.insertBefore(this.cloneNode(deep), this.nextSibling);
});
```

## _selection_.sort( _compare_) [​](https://d3js.org/d3-selection/modifying\#selection_sort)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/sort.js) · Returns a new selection that contains a copy of each group in this selection sorted according to the _compare_ function. After sorting, re-inserts elements to match the resulting order (per [_selection_.order](https://d3js.org/d3-selection/modifying#selection_order)).

The compare function, which defaults to [ascending](https://d3js.org/d3-array/sort#ascending), is passed two elements’ data _a_ and _b_ to compare. It should return either a negative, positive, or zero value. If negative, then _a_ should be before _b_; if positive, then _a_ should be after _b_; otherwise, _a_ and _b_ are considered equal and the order is arbitrary.

## _selection_.order() [​](https://d3js.org/d3-selection/modifying\#selection_order)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/order.js) · Re-inserts elements into the document such that the document order of each group matches the selection order. This is equivalent to calling [_selection_.sort](https://d3js.org/d3-selection/modifying#selection_sort) if the data is already sorted, but much faster.

## _selection_.raise() [​](https://d3js.org/d3-selection/modifying\#selection_raise)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/raise.js) · Re-inserts each selected element, in order, as the last child of its parent. Equivalent to:

js

```
selection.each(function() {
  this.parentNode.appendChild(this);
});
```

## _selection_.lower() [​](https://d3js.org/d3-selection/modifying\#selection_lower)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/lower.js) · Re-inserts each selected element, in order, as the first child of its parent. Equivalent to:

js

```
selection.each(function() {
  this.parentNode.insertBefore(this, this.parentNode.firstChild);
});
```

## create( _name_) [​](https://d3js.org/d3-selection/modifying\#create)

[Source](https://github.com/d3/d3-selection/blob/main/src/create.js) · Given the specified element _name_, returns a single-element selection containing a detached element of the given name in the current document. This method assumes the HTML namespace, so you must specify a namespace explicitly when creating SVG or other non-HTML elements; see [namespace](https://d3js.org/d3-selection/namespaces#namespace) for details on supported namespace prefixes.

js

```
d3.create("svg") // equivalent to svg:svg
```

js

```
d3.create("svg:svg") // more explicitly
```

js

```
d3.create("svg:g") // an SVG G element
```

js

```
d3.create("g") // an HTML G (unknown) element
```

## creator( _name_) [​](https://d3js.org/d3-selection/modifying\#creator)

[Source](https://github.com/d3/d3-selection/blob/main/src/creator.js) · Given the specified element _name_, returns a function which creates an element of the given name, assuming that `this` is the parent element. This method is used internally by [_selection_.append](https://d3js.org/d3-selection/modifying#selection_append) and [_selection_.insert](https://d3js.org/d3-selection/modifying#selection_insert) to create new elements. For example, this:

js

```
selection.append("div");
```

Is equivalent to:

js

```
selection.append(d3.creator("div"));
```

See [namespace](https://d3js.org/d3-selection/namespaces#namespace) for details on supported namespace prefixes, such as for SVG elements.

## D3 Local Variables
[Skip to content](https://d3js.org/d3-selection/locals#VPContent)

On this page

# Local variables [​](https://d3js.org/d3-selection/locals\#local-variables)

D3 locals allow you to define local state independent of data. For instance, when rendering [small multiples](https://gist.github.com/mbostock/e1192fe405703d8321a5187350910e08) of time-series data, you might want the same x scale for all charts but distinct y scales to compare the relative performance of each metric. D3 locals are scoped by DOM elements: on set, the value is stored on the given element; on get, the value is retrieved from given element or the nearest ancestor that defines it.

CAUTION

Locals are rarely used; you may find it easier to store whatever state you need in the selection’s data.

## local() [​](https://d3js.org/d3-selection/locals\#local)

[Source](https://github.com/d3/d3-selection/blob/main/src/local.js) · Declares a new local variable.

js

```
const foo = d3.local();
```

Like `var`, each local is a distinct symbolic reference; unlike `var`, the value of each local is also scoped by the DOM.

## _local_.set( _node_, _value_) [​](https://d3js.org/d3-selection/locals\#local_set)

[Source](https://github.com/d3/d3-selection/blob/main/src/local.js) · Sets the value of this local on the specified _node_ to the _value_, and returns the specified _value_. This is often performed using [_selection_.each](https://d3js.org/d3-selection/control-flow#selection_each):

js

```
selection.each(function(d) {
  foo.set(this, d.value);
});
```

If you are just setting a single variable, consider using [_selection_.property](https://d3js.org/d3-selection/modifying#selection_property):

js

```
selection.property(foo, (d) => d.value);
```

## _local_.get( _node_) [​](https://d3js.org/d3-selection/locals\#local_get)

[Source](https://github.com/d3/d3-selection/blob/main/src/local.js) · Returns the value of this local on the specified _node_.

js

```
selection.each(function() {
  const value = foo.get(this);
});
```

If the _node_ does not define this local, returns the value from the nearest ancestor that defines it. Returns undefined if no ancestor defines this local.

## _local_.remove( _node_) [​](https://d3js.org/d3-selection/locals\#local_remove)

[Source](https://github.com/d3/d3-selection/blob/main/src/local.js) · Deletes this local’s value from the specified _node_.

js

```
selection.each(function() {
  foo.remove(this);
});
```

Returns true if the _node_ defined this local prior to removal, and false otherwise. If ancestors also define this local, those definitions are unaffected, and thus [_local_.get](https://d3js.org/d3-selection/locals#local_get) will still return the inherited value.

## _local_.toString() [​](https://d3js.org/d3-selection/locals\#local_toString)

[Source](https://github.com/d3/d3-selection/blob/main/src/local.js) · Returns the automatically-generated identifier for this local. This is the name of the property that is used to store the local’s value on elements, and thus you can also set or get the local’s value using _element_\[ _local_\] or by using [_selection_.property](https://d3js.org/d3-selection/modifying#selection_property).

## D3 Chord Diagrams
[Skip to content](https://d3js.org/d3-chord/chord#VPContent)

On this page

# Chords [​](https://d3js.org/d3-chord/chord\#chords)

The chord layout computes angles to generate a [chord diagram](https://d3js.org/d3-chord).

## chord() [​](https://d3js.org/d3-chord/chord\#chord)

[Source](https://github.com/d3/d3-chord/blob/main/src/chord.js) · Constructs a new chord layout with the default settings.

js

```
const chord = d3.chord();
```

## _chord_( _matrix_) [​](https://d3js.org/d3-chord/chord\#_chord)

[Source](https://github.com/d3/d3-chord/blob/main/src/chord.js) · Computes the chord layout for the specified square _matrix_ of size _n_ × _n_, where the _matrix_ represents the directed flow amongst a network (a complete digraph) of _n_ nodes.

The return value of _chord_( _matrix_) is an array of _chords_, where each chord represents the combined bidirectional flow between two nodes _i_ and _j_ (where _i_ may be equal to _j_) and is an object with the following properties:

- `source` \- the source subgroup
- `target` \- the target subgroup

Each source and target subgroup is also an object with the following properties:

- `startAngle` \- the start angle in radians
- `endAngle` \- the end angle in radians
- `value` \- the flow value _matrix_\[ _i_\]\[ _j_\]
- `index` \- the node index _i_

The chords are typically passed to [ribbon](https://d3js.org/d3-chord/ribbon) to display the network relationships.

The returned array includes only chord objects for which the value _matrix_\[ _i_\]\[ _j_\] or _matrix_\[ _j_\]\[ _i_\] is non-zero. Furthermore, the returned array only contains unique chords: a given chord _ij_ represents the bidirectional flow from _i_ to _j_ _and_ from _j_ to _i_, and does not contain a duplicate chord _ji_; _i_ and _j_ are chosen such that the chord’s source always represents the larger of _matrix_\[ _i_\]\[ _j_\] and _matrix_\[ _j_\]\[ _i_\].

The _chords_ array also defines a secondary array of length _n_, _chords_.groups, where each group represents the combined outflow for node _i_, corresponding to the elements _matrix_\[ _i_\]\[0 … _n_ \- 1\], and is an object with the following properties:

- `startAngle` \- the start angle in radians
- `endAngle` \- the end angle in radians
- `value` \- the total outgoing flow value for node _i_
- `index` \- the node index _i_

The groups are typically passed to [arc](https://d3js.org/d3-shape/arc) to produce a donut chart around the circumference of the chord layout.

## _chord_.padAngle( _angle_) [​](https://d3js.org/d3-chord/chord\#chord_padAngle)

[Source](https://github.com/d3/d3-chord/blob/main/src/chord.js) · If _angle_ is specified, sets the pad angle between adjacent groups to the specified number in radians and returns this chord layout. If _angle_ is not specified, returns the current pad angle, which defaults to zero.

## _chord_.sortGroups( _compare_) [​](https://d3js.org/d3-chord/chord\#chord_sortGroups)

[Source](https://github.com/d3/d3-chord/blob/main/src/chord.js) · If _compare_ is specified, sets the group comparator to the specified function or null and returns this chord layout. If _compare_ is not specified, returns the current group comparator, which defaults to null. If the group comparator is non-null, it is used to sort the groups by their total outflow. See also [ascending](https://d3js.org/d3-array/sort#ascending) and [descending](https://d3js.org/d3-array/sort#descending).

## _chord_.sortSubgroups( _compare_) [​](https://d3js.org/d3-chord/chord\#chord_sortSubgroups)

[Source](https://github.com/d3/d3-chord/blob/main/src/chord.js) · If _compare_ is specified, sets the subgroup comparator to the specified function or null and returns this chord layout. If _compare_ is not specified, returns the current subgroup comparator, which defaults to null. If the subgroup comparator is non-null, it is used to sort the subgroups corresponding to _matrix_\[ _i_\]\[0 … _n_ \- 1\] for a given group _i_ by their total outflow. See also [ascending](https://d3js.org/d3-array/sort#ascending) and [descending](https://d3js.org/d3-array/sort#descending).

## _chord_.sortChords( _compare_) [​](https://d3js.org/d3-chord/chord\#chord_sortChords)

[Source](https://github.com/d3/d3-chord/blob/main/src/chord.js) · If _compare_ is specified, sets the chord comparator to the specified function or null and returns this chord layout. If _compare_ is not specified, returns the current chord comparator, which defaults to null. If the chord comparator is non-null, it is used to sort the [chords](https://d3js.org/d3-chord/chord#_chord) by their combined flow; this only affects the _z_-order of the chords. See also [ascending](https://d3js.org/d3-array/sort#ascending) and [descending](https://d3js.org/d3-array/sort#descending).

## chordDirected() [​](https://d3js.org/d3-chord/chord\#chordDirected)

[Examples](https://observablehq.com/@d3/directed-chord-diagram) · [Source](https://github.com/d3/d3-chord/blob/main/src/chord.js) · A chord layout for unidirectional flows. The chord from _i_ to _j_ is generated from the value in _matrix_\[ _i_\]\[ _j_\] only.

## chordTranspose() [​](https://d3js.org/d3-chord/chord\#chordTranspose)

[Source](https://github.com/d3/d3-chord/blob/main/src/chord.js) · A transposed chord layout. Useful to highlight outgoing (rather than incoming) flows.

## D3.js Curve Types
[Skip to content](https://d3js.org/d3-shape/curve#VPContent)

On this page

# Curves [​](https://d3js.org/d3-shape/curve\#curves)

Curves turn a discrete (pointwise) representation of a [line](https://d3js.org/d3-shape/line) or [area](https://d3js.org/d3-shape/area) into a continuous shape: curves specify how to interpolate between two-dimensional \[ _x_, _y_\] points.

Curves are typically not constructed or used directly. Instead, one of the built-in curves is being passed to [_line_.curve](https://d3js.org/d3-shape/line#line_curve) or [_area_.curve](https://d3js.org/d3-shape/area#area_curve).

js

```
const line = d3.line()
    .x((d) => x(d.date))
    .y((d) => y(d.value))
    .curve(d3.curveCatmullRom.alpha(0.5));
```

If desired, you can implement a [custom curve](https://d3js.org/d3-shape/curve#custom-curves). For an example of using a curve directly, see [Context to Curve](https://observablehq.com/@d3/context-to-curve).

## _curveBasis_( _context_) [​](https://d3js.org/d3-shape/curve\#curveBasis)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/basis.js) · Produces a cubic [basis spline](https://en.wikipedia.org/wiki/B-spline) using the specified control points. The first and last points are triplicated such that the spline starts at the first point and ends at the last point, and is tangent to the line between the first and second points, and to the line between the penultimate and last points.

## _curveBasisClosed_( _context_) [​](https://d3js.org/d3-shape/curve\#curveBasisClosed)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/basisClosed.js) · Produces a closed cubic [basis spline](https://en.wikipedia.org/wiki/B-spline) using the specified control points. When a line segment ends, the first three control points are repeated, producing a closed loop with C2 continuity.

## _curveBasisOpen_( _context_) [​](https://d3js.org/d3-shape/curve\#curveBasisOpen)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/basisOpen.js) · Produces a cubic [basis spline](https://en.wikipedia.org/wiki/B-spline) using the specified control points. Unlike [basis](https://d3js.org/d3-shape/curve#curveBasis), the first and last points are not repeated, and thus the curve typically does not intersect these points.

## _curveBumpX_( _context_) [​](https://d3js.org/d3-shape/curve\#curveBumpX)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/bump.js) · Produces a Bézier curve between each pair of points, with horizontal tangents at each point.

## _curveBumpY_( _context_) [​](https://d3js.org/d3-shape/curve\#curveBumpY)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/bump.js) · Produces a Bézier curve between each pair of points, with vertical tangents at each point.

## _curveBundle_( _context_) [​](https://d3js.org/d3-shape/curve\#curveBundle)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/bundle.js) · Produces a straightened cubic [basis spline](https://en.wikipedia.org/wiki/B-spline) using the specified control points, with the spline straightened according to the curve’s [_beta_](https://d3js.org/d3-shape/curve#curveBundle_beta), which defaults to 0.85. This curve is typically used in [hierarchical edge bundling](https://observablehq.com/@d3/hierarchical-edge-bundling) to disambiguate connections, as proposed by [Danny Holten](https://www.win.tue.nl/vis1/home/dholten/) in [Hierarchical Edge Bundles: Visualization of Adjacency Relations in Hierarchical Data](https://www.win.tue.nl/vis1/home/dholten/papers/bundles_infovis.pdf). This curve does not implement [_curve_.areaStart](https://d3js.org/d3-shape/curve#curve_areaStart) and [_curve_.areaEnd](https://d3js.org/d3-shape/curve#curve_areaEnd); it is intended to work with [d3.line](https://d3js.org/d3-shape/line), not [d3.area](https://d3js.org/d3-shape/area).

## curveBundle.beta( _beta_) [​](https://d3js.org/d3-shape/curve\#curveBundle_beta)

Beta:0.85

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/bundle.js) · Returns a bundle curve with the specified _beta_ in the range \[0, 1\], representing the bundle strength. If _beta_ equals zero, a straight line between the first and last point is produced; if _beta_ equals one, a standard [basis](https://d3js.org/d3-shape/curve#curveBasis) spline is produced. For example:

js

```
const line = d3.line().curve(d3.curveBundle.beta(0.5));
```

## _curveCardinal_( _context_) [​](https://d3js.org/d3-shape/curve\#curveCardinal)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/cardinal.js) · Produces a cubic [cardinal spline](https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Cardinal_spline) using the specified control points, with one-sided differences used for the first and last piece. The default [tension](https://d3js.org/d3-shape/curve#curveCardinal_tension) is 0.

## _curveCardinalClosed_( _context_) [​](https://d3js.org/d3-shape/curve\#curveCardinalClosed)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/cardinalClosed.js) · Produces a closed cubic [cardinal spline](https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Cardinal_spline) using the specified control points. When a line segment ends, the first three control points are repeated, producing a closed loop. The default [tension](https://d3js.org/d3-shape/curve#curveCardinal_tension) is 0.

## _curveCardinalOpen_( _context_) [​](https://d3js.org/d3-shape/curve\#curveCardinalOpen)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/cardinalOpen.js) · Produces a cubic [cardinal spline](https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Cardinal_spline) using the specified control points. Unlike [curveCardinal](https://d3js.org/d3-shape/curve#curveCardinal), one-sided differences are not used for the first and last piece, and thus the curve starts at the second point and ends at the penultimate point. The default [tension](https://d3js.org/d3-shape/curve#curveCardinal_tension) is 0.

## curveCardinal.tension( _tension_) [​](https://d3js.org/d3-shape/curve\#curveCardinal_tension)

Tension:0.00

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/cardinalOpen.js) · Returns a cardinal curve with the specified _tension_ in the range \[0, 1\]. The _tension_ determines the length of the tangents: a _tension_ of one yields all zero tangents, equivalent to [curveLinear](https://d3js.org/d3-shape/curve#curveLinear); a _tension_ of zero produces a uniform [Catmull–Rom](https://d3js.org/d3-shape/curve#curveCatmullRom) spline. For example:

js

```
const line = d3.line().curve(d3.curveCardinal.tension(0.5));
```

## _curveCatmullRom_( _context_) [​](https://d3js.org/d3-shape/curve\#curveCatmullRom)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/catmullRom.js) · Produces a cubic Catmull–Rom spline using the specified control points and the parameter [_alpha_](https://d3js.org/d3-shape/curve#curveCatmullRom_alpha), which defaults to 0.5, as proposed by Yuksel et al. in [On the Parameterization of Catmull–Rom Curves](http://www.cemyuksel.com/research/catmullrom_param/), with one-sided differences used for the first and last piece.

## _curveCatmullRomClosed_( _context_) [​](https://d3js.org/d3-shape/curve\#curveCatmullRomClosed)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/catmullRomClosed.js) · Produces a closed cubic Catmull–Rom spline using the specified control points and the parameter [_alpha_](https://d3js.org/d3-shape/curve#curveCatmullRom_alpha), which defaults to 0.5, as proposed by Yuksel et al. When a line segment ends, the first three control points are repeated, producing a closed loop.

## _curveCatmullRomOpen_( _context_) [​](https://d3js.org/d3-shape/curve\#curveCatmullRomOpen)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/catmullRomOpen.js) · Produces a cubic Catmull–Rom spline using the specified control points and the parameter [_alpha_](https://d3js.org/d3-shape/curve#curveCatmullRom_alpha), which defaults to 0.5, as proposed by Yuksel et al. Unlike [curveCatmullRom](https://d3js.org/d3-shape/curve#curveCatmullRom), one-sided differences are not used for the first and last piece, and thus the curve starts at the second point and ends at the penultimate point.

## curveCatmullRom.alpha( _alpha_) [​](https://d3js.org/d3-shape/curve\#curveCatmullRom_alpha)

Alpha:0.50

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/catmullRom.js) · Returns a cubic Catmull–Rom curve with the specified _alpha_ in the range \[0, 1\]. If _alpha_ is zero, produces a uniform spline, equivalent to [curveCardinal](https://d3js.org/d3-shape/curve#curveCardinal) with a tension of zero; if _alpha_ is one, produces a chordal spline; if _alpha_ is 0.5, produces a [centripetal spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline). Centripetal splines are recommended to avoid self-intersections and overshoot. For example:

js

```
const line = d3.line().curve(d3.curveCatmullRom.alpha(0.5));
```

## _curveLinear_( _context_) [​](https://d3js.org/d3-shape/curve\#curveLinear)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/linear.js) · Produces a polyline through the specified points.

## _curveLinearClosed_( _context_) [​](https://d3js.org/d3-shape/curve\#curveLinearClosed)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/linearClosed.js) · Produces a closed polyline through the specified points by repeating the first point when the line segment ends.

## _curveMonotoneX_( _context_) [​](https://d3js.org/d3-shape/curve\#curveMonotoneX)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/monotone.js) · Produces a cubic spline that [preserves monotonicity](https://en.wikipedia.org/wiki/Monotone_cubic_interpolation) in _y_, assuming monotonicity in _x_, as proposed by Steffen in [A simple method for monotonic interpolation in one dimension](http://adsabs.harvard.edu/full/1990A%26A...239..443S): “a smooth curve with continuous first-order derivatives that passes through any given set of data points without spurious oscillations. Local extrema can occur only at grid points where they are given by the data, but not in between two adjacent grid points.”

## _curveMonotoneY_( _context_) [​](https://d3js.org/d3-shape/curve\#curveMonotoneY)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/monotone.js) · Produces a cubic spline that [preserves monotonicity](https://en.wikipedia.org/wiki/Monotone_cubic_interpolation) in _x_, assuming monotonicity in _y_, as proposed by Steffen in [A simple method for monotonic interpolation in one dimension](http://adsabs.harvard.edu/full/1990A%26A...239..443S): “a smooth curve with continuous first-order derivatives that passes through any given set of data points without spurious oscillations. Local extrema can occur only at grid points where they are given by the data, but not in between two adjacent grid points.”

## _curveNatural_( _context_) [​](https://d3js.org/d3-shape/curve\#curveNatural)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/natural.js) · Produces a [natural](https://en.wikipedia.org/wiki/Spline_interpolation) [cubic spline](http://mathworld.wolfram.com/CubicSpline.html) with the second derivative of the spline set to zero at the endpoints.

## _curveStep_( _context_) [​](https://d3js.org/d3-shape/curve\#curveStep)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/step.js) · Produces a piecewise constant function (a [step function](https://en.wikipedia.org/wiki/Step_function)) consisting of alternating horizontal and vertical lines. The _y_-value changes at the midpoint of each pair of adjacent _x_-values.

## _curveStepAfter_( _context_) [​](https://d3js.org/d3-shape/curve\#curveStepAfter)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/step.js) · Produces a piecewise constant function (a [step function](https://en.wikipedia.org/wiki/Step_function)) consisting of alternating horizontal and vertical lines. The _y_-value changes after the _x_-value.

## _curveStepBefore_( _context_) [​](https://d3js.org/d3-shape/curve\#curveStepBefore)

[Source](https://github.com/d3/d3-shape/blob/main/src/curve/step.js) · Produces a piecewise constant function (a [step function](https://en.wikipedia.org/wiki/Step_function)) consisting of alternating horizontal and vertical lines. The _y_-value changes before the _x_-value.

## Custom curves [​](https://d3js.org/d3-shape/curve\#custom-curves)

Curves are typically not used directly, instead being passed to [_line_.curve](https://d3js.org/d3-shape/line#line_curve) and [_area_.curve](https://d3js.org/d3-shape/area#area_curve). However, you can define your own curve implementation should none of the built-in curves satisfy your needs using the following interface; see the [curveLinear source](https://github.com/d3/d3-shape/blob/main/src/curve/linear.js) for an example implementation. You can also use this low-level interface with a built-in curve type as an alternative to the line and area generators.

### _curve_.areaStart() [​](https://d3js.org/d3-shape/curve\#curve_areaStart)

Indicates the start of a new area segment. Each area segment consists of exactly two [line segments](https://d3js.org/d3-shape/curve#curve_lineStart): the topline, followed by the baseline, with the baseline points in reverse order.

### _curve_.areaEnd() [​](https://d3js.org/d3-shape/curve\#curve_areaEnd)

Indicates the end of the current area segment.

### _curve_.lineStart() [​](https://d3js.org/d3-shape/curve\#curve_lineStart)

Indicates the start of a new line segment. Zero or more [points](https://d3js.org/d3-shape/curve#curve_point) will follow.

### _curve_.lineEnd() [​](https://d3js.org/d3-shape/curve\#curve_lineEnd)

Indicates the end of the current line segment.

### _curve_.point( _x_, _y_) [​](https://d3js.org/d3-shape/curve\#curve_point)

Indicates a new point in the current line segment with the given _x_\- and _y_-values.

## Voronoi Diagrams
[Skip to content](https://d3js.org/d3-delaunay/voronoi#VPContent)

On this page

# Voronoi diagrams [​](https://d3js.org/d3-delaunay/voronoi\#voronoi-diagrams)

Given a set of points, the Voronoi diagram partitions the plane into cells representing the region of the plane that is closest to the corresponding point. The Voronoi diagram is the dual of the [Delaunay triangulation](https://d3js.org/d3-delaunay/delaunay).

## _delaunay_.voronoi( _bounds_) [​](https://d3js.org/d3-delaunay/voronoi\#delaunay_voronoi)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Returns the Voronoi diagram for the given [Delaunay triangulation](https://d3js.org/d3-delaunay/delaunay). When rendering, the diagram will be clipped to the specified _bounds_ = \[ _xmin_, _ymin_, _xmax_, _ymax_\].

js

```
const delaunay = d3.Delaunay.from([[0, 0], [0, 100], [100, 0], [100, 100]]);
const voronoi = delaunay.voronoi([0, 0, 640, 480]);
```

If _bounds_ is not specified, it defaults to \[0, 0, 960, 500\]. The Voronoi diagram is returned even in degenerate cases where no triangulation exists — namely 0, 1 or 2 points, and collinear points.

### _voronoi_.delaunay [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_delaunay)

The Voronoi diagram’s associated [Delaunay triangulation](https://d3js.org/d3-delaunay/delaunay).

### _voronoi_.circumcenters [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_circumcenters)

The [circumcenters](http://mathworld.wolfram.com/Circumcenter.html) of the Delaunay triangles as a Float64Array \[ _cx0_, _cy0_, _cx1_, _cy1_, …\]. Each contiguous pair of coordinates _cx_, _cy_ is the circumcenter for the corresponding triangle. These circumcenters form the coordinates of the Voronoi cell polygons.

### _voronoi_.vectors [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_vectors)

A Float64Array \[ _vx0_, _vy0_, _wx0_, _wy0_, …\] where each non-zero quadruple describes an open (infinite) cell on the outer hull, giving the directions of two open half-lines.

### _voronoi_.xmin  _voronoi_.ymin  _voronoi_.xmax  _voronoi_.ymax [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_bounds)

The bounds of the viewport \[ _xmin_, _ymin_, _xmax_, _ymax_\] for rendering the Voronoi diagram. These values only affect the rendering methods ( [_voronoi_.render](https://d3js.org/d3-delaunay/voronoi#voronoi_render), [_voronoi_.renderBounds](https://d3js.org/d3-delaunay/voronoi#voronoi_renderBounds), [_voronoi_.renderCell](https://d3js.org/d3-delaunay/voronoi#voronoi_renderCell)).

## _voronoi_.contains( _i_, _x_, _y_) [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_contains)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/voronoi.js) · Returns true if the cell with the specified index _i_ contains the specified point ⟨ _x_, _y_⟩; _i.e._, whether the point _i_ is the closest point in the diagram to the specified point. (This method is not affected by the associated Voronoi diagram’s viewport [bounds](https://d3js.org/d3-delaunay/voronoi#voronoi_bounds).)

## _voronoi_.neighbors( _i_) [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_neighbors)

js

```
voronoi.neighbors(353) // [712, 521, 351, 358, 384]
```

[Source](https://github.com/d3/d3-delaunay/blob/main/src/voronoi.js) · Returns an iterable over the indexes of the cells that share a common edge with the specified cell _i_. Voronoi neighbors are always neighbors on the Delaunay graph, but the converse is false when the common edge has been clipped out by the Voronoi diagram’s viewport.

## _voronoi_.render( _context_) [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_render)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/voronoi.js) · Renders the mesh of Voronoi cells to the specified _context_. The specified _context_ must implement the _context_.moveTo and _context_.lineTo methods from the [CanvasPathMethods API](https://www.w3.org/TR/2dcontext/#canvaspathmethods). If a _context_ is not specified, an SVG path string is returned instead.

## _voronoi_.renderBounds( _context_) [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_renderBounds)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/voronoi.js) · Renders the viewport extent to the specified _context_. The specified _context_ must implement the _context_.rect method from the [CanvasPathMethods API](https://www.w3.org/TR/2dcontext/#canvaspathmethods). Equivalent to _context_.rect( _voronoi_.xmin, _voronoi_.ymin, _voronoi_.xmax - _voronoi_.xmin, _voronoi_.ymax - _voronoi_.ymin). If a _context_ is not specified, an SVG path string is returned instead.

## _voronoi_.renderCell( _i_, _context_) [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_renderCell)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/voronoi.js) · Renders the cell with the specified index _i_ to the specified _context_. The specified _context_ must implement the _context_.moveTo , _context_.lineTo and _context_.closePath methods from the [CanvasPathMethods API](https://www.w3.org/TR/2dcontext/#canvaspathmethods). If a _context_ is not specified, an SVG path string is returned instead.

## _voronoi_.cellPolygons() [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_cellPolygons)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/voronoi.js) · Returns an iterable over the non-empty [polygons for each cell](https://d3js.org/d3-delaunay/voronoi#voronoi_cellPolygon), with the cell index as property. See also [_voronoi_.renderCell](https://d3js.org/d3-delaunay/voronoi#voronoi_renderCell).

## _voronoi_.cellPolygon( _i_) [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_cellPolygon)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/voronoi.js) · Returns the convex, closed polygon \[\[ _x0_, _y0_\], \[ _x1_, _y1_\], …, \[ _x0_, _y0_\]\] representing the cell for the specified point _i_. See also [_voronoi_.renderCell](https://d3js.org/d3-delaunay/voronoi#voronoi_renderCell).

## _voronoi_.update() [​](https://d3js.org/d3-delaunay/voronoi\#voronoi_update)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/voronoi.js) · Updates the Voronoi diagram and underlying triangulation after the points have been modified in-place — useful for Lloyd’s relaxation. Calls [_delaunay_.update](https://d3js.org/d3-delaunay/delaunay#delaunay_update) on the underlying Delaunay triangulation.

## D3.js Zoom Features
[Skip to content](https://d3js.org/d3-zoom#VPContent)

On this page

# d3-zoom [​](https://d3js.org/d3-zoom\#d3-zoom)

[Examples](https://observablehq.com/collection/@d3/d3-zoom) · [Panning and zooming](https://observablehq.com/@d3/zoomable-scatterplot) let the user focus on a region of interest by restricting the view. It uses direct manipulation: click-and-drag to pan (translate), spin the wheel to zoom (scale), or pinch with touch. Panning and zooming are widely used in web-based mapping, but can also be used in visualization such as dense time series and scatterplots.

The zoom behavior is a flexible abstraction, handling a surprising variety of input modalities and browser quirks. The zoom behavior is agnostic about the DOM, so you can use it with HTML, [SVG](https://observablehq.com/@d3/zoom), or [Canvas](https://observablehq.com/@d3/zoom-canvas). You can use d3-zoom with [d3-scale](https://d3js.org/d3-scale) and [d3-axis](https://d3js.org/d3-axis) to [zoom axes](https://observablehq.com/@d3/pan-zoom-axes). You can restrict zooming using [_zoom_.scaleExtent](https://d3js.org/d3-zoom#zoom_scaleExtent) and panning using [_zoom_.translateExtent](https://d3js.org/d3-zoom#zoom_translateExtent). You can combine d3-zoom with other behaviors such as [d3-drag](https://d3js.org/d3-drag) for [dragging](https://observablehq.com/@d3/drag-zoom) and [d3-brush](https://d3js.org/d3-brush) for [focus + context](https://observablehq.com/@d3/focus-context).

The zoom behavior can be controlled programmatically using [_zoom_.transform](https://d3js.org/d3-zoom#zoom_transform), allowing you to implement user interface controls which drive the display or to stage [animated tours](https://observablehq.com/@d3/scatterplot-tour) through your data. [Smooth zoom transitions](https://observablehq.com/@d3/programmatic-zoom) are based on [“Smooth and efficient zooming and panning”](http://www.win.tue.nl/~vanwijk/zoompan.pdf) by Jarke J. van Wijk and Wim A.A. Nuij.

See also [d3-tile](https://github.com/d3/d3-tile) for examples panning and zooming maps.

## zoom() [​](https://d3js.org/d3-zoom\#zoom)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · Creates a new zoom behavior. The returned behavior, [_zoom_](https://d3js.org/d3-zoom#_zoom), is both an object and a function, and is typically applied to selected elements via [_selection_.call](https://d3js.org/d3-selection/control-flow#selection_call).

## _zoom_( _selection_) [​](https://d3js.org/d3-zoom\#_zoom)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · Applies this zoom behavior to the specified [_selection_](https://d3js.org/d3-selection), binding the necessary event listeners to allow panning and zooming, and initializing the [zoom transform](https://d3js.org/d3-zoom#zoomTransform) on each selected element to the identity transform if not already defined.

This function is typically not invoked directly, and is instead invoked via [_selection_.call](https://d3js.org/d3-selection/control-flow#selection_call). For example, to instantiate a zoom behavior and apply it to a selection:

js

```
selection.call(d3.zoom().on("zoom", zoomed));
```

Internally, the zoom behavior uses [_selection_.on](https://d3js.org/d3-selection/events#selection_on) to bind the necessary event listeners for zooming. The listeners use the name `.zoom`, so you can subsequently unbind the zoom behavior as follows:

js

```
selection.on(".zoom", null);
```

To disable just wheel-driven zooming (say to not interfere with native scrolling), you can remove the zoom behavior’s wheel event listener after applying the zoom behavior to the selection:

js

```
selection
    .call(zoom)
    .on("wheel.zoom", null);
```

Alternatively, use [_zoom_.filter](https://d3js.org/d3-zoom#zoom_filter) for greater control over which events can initiate zoom gestures.

Applying the zoom behavior also sets the [-webkit-tap-highlight-color](https://developer.apple.com/library/mac/documentation/AppleApplications/Reference/SafariWebContent/AdjustingtheTextSize/AdjustingtheTextSize.html#//apple_ref/doc/uid/TP40006510-SW5) style to transparent, disabling the tap highlight on iOS. If you want a different tap highlight color, remove or re-apply this style after applying the drag behavior.

The zoom behavior stores the zoom state on the element to which the zoom behavior was applied, not on the zoom behavior itself. This allows the zoom behavior to be applied to many elements simultaneously with independent zooming. The zoom state can change either on user interaction or programmatically via [_zoom_.transform](https://d3js.org/d3-zoom#zoom_transform).

To retrieve the zoom state, use _event_.transform on the current [zoom event](https://d3js.org/d3-zoom#zoom-events) within a zoom event listener (see [_zoom_.on](https://d3js.org/d3-zoom#zoom_on)), or use [zoomTransform](https://d3js.org/d3-zoom#zoomTransform) for a given node. The latter is useful for modifying the zoom state programmatically, say to implement buttons for zooming in and out.

## _zoom_.transform( _selection_, _transform_, _point_) [​](https://d3js.org/d3-zoom\#zoom_transform)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _selection_ is a selection, sets the [current zoom transform](https://d3js.org/d3-zoom#zoomTransform) of the selected elements to the specified _transform_, instantaneously emitting start, zoom and end [events](https://d3js.org/d3-zoom#zoom-events).

If _selection_ is a transition, defines a “zoom” tween to the specified _transform_ using [interpolateZoom](https://d3js.org/d3-interpolate/zoom#interpolateZoom), emitting a start event when the transition starts, zoom events for each tick of the transition, and then an end event when the transition ends (or is interrupted). The transition will attempt to minimize the visual movement around the specified _point_; if the _point_ is not specified, it defaults to the center of the viewport [extent](https://d3js.org/d3-zoom#zoom_extent).

The _transform_ may be specified either as a [zoom transform](https://d3js.org/d3-zoom#zoomTransform) or as a function that returns a zoom transform; similarly, the _point_ may be specified either as a two-element array \[ _x_, _y_\] or a function that returns such an array. If a function, it is invoked for each selected element, being passed the current event ( `event`) and datum `d`, with the `this` context as the current DOM element.

This function is typically not invoked directly, and is instead invoked via [_selection_.call](https://d3js.org/d3-selection/control-flow#selection_call) or [_transition_.call](https://d3js.org/d3-transition/control-flow#transition_call). For example, to reset the zoom transform to the [identity transform](https://d3js.org/d3-zoom#zoomIdentity) instantaneously:

js

```
selection.call(zoom.transform, d3.zoomIdentity);
```

To smoothly reset the zoom transform to the identity transform over 750 milliseconds:

js

```
selection.transition().duration(750).call(zoom.transform, d3.zoomIdentity);
```

This method requires that you specify the new zoom transform completely, and does not enforce the defined [scale extent](https://d3js.org/d3-zoom#zoom_scaleExtent) and [translate extent](https://d3js.org/d3-zoom#zoom_translateExtent), if any. To derive a new transform from the existing transform, and to enforce the scale and translate extents, see the convenience methods [_zoom_.translateBy](https://d3js.org/d3-zoom#zoom_translateBy), [_zoom_.scaleBy](https://d3js.org/d3-zoom#zoom_scaleBy) and [_zoom_.scaleTo](https://d3js.org/d3-zoom#zoom_scaleTo).

## _zoom_.translateBy( _selection_, _x_, _y_) [​](https://d3js.org/d3-zoom\#zoom_translateBy)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _selection_ is a selection, [translates](https://d3js.org/d3-zoom#transform_translate) the [current zoom transform](https://d3js.org/d3-zoom#zoomTransform) of the selected elements by _x_ and _y_, such that the new _tx1_ = _tx0_ \+ _kx_ and _ty1_ = _ty0_ \+ _ky_. If _selection_ is a transition, defines a “zoom” tween translating the current transform. This method is a convenience method for [_zoom_.transform](https://d3js.org/d3-zoom#zoom_transform). The _x_ and _y_ translation amounts may be specified either as numbers or as functions that return numbers. 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.

## _zoom_.translateTo( _selection_, _x_, _y_, _p_) [​](https://d3js.org/d3-zoom\#zoom_translateTo)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _selection_ is a selection, [translates](https://d3js.org/d3-zoom#transform_translate) the [current zoom transform](https://d3js.org/d3-zoom#zoomTransform) of the selected elements such that the given position ⟨ _x_, _y_⟩ appears at given point _p_. The new _tx_ = _px_ \- _kx_ and _ty_ = _py_ \- _ky_. If _p_ is not specified, it defaults to the center of the viewport [extent](https://d3js.org/d3-zoom#zoom_extent). If _selection_ is a transition, defines a “zoom” tween translating the current transform. This method is a convenience method for [_zoom_.transform](https://d3js.org/d3-zoom#zoom_transform). The _x_ and _y_ coordinates may be specified either as numbers or as functions that returns numbers; similarly the _p_ point may be specified either as a two-element array \[ _px_, _py_\] or a function. 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.

## _zoom_.scaleBy( _selection_, _k_, _p_) [​](https://d3js.org/d3-zoom\#zoom_scaleBy)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _selection_ is a selection, [scales](https://d3js.org/d3-zoom#transform_scale) the [current zoom transform](https://d3js.org/d3-zoom#zoomTransform) of the selected elements by _k_, such that the new _k₁_ = _k₀k_. The reference point _p_ does move. If _p_ is not specified, it defaults to the center of the viewport [extent](https://d3js.org/d3-zoom#zoom_extent). If _selection_ is a transition, defines a “zoom” tween translating the current transform. This method is a convenience method for [_zoom_.transform](https://d3js.org/d3-zoom#zoom_transform). The _k_ scale factor may be specified either as a number or a function that returns a number; similarly the _p_ point may be specified either as a two-element array \[ _px_, _py_\] or a function. 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.

## _zoom_.scaleTo( _selection_, _k_, _p_) [​](https://d3js.org/d3-zoom\#zoom_scaleTo)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _selection_ is a selection, [scales](https://d3js.org/d3-zoom#transform_scale) the [current zoom transform](https://d3js.org/d3-zoom#zoomTransform) of the selected elements to _k_, such that the new _k₁_ = _k_. The reference point _p_ does move. If _p_ is not specified, it defaults to the center of the viewport [extent](https://d3js.org/d3-zoom#zoom_extent). If _selection_ is a transition, defines a “zoom” tween translating the current transform. This method is a convenience method for [_zoom_.transform](https://d3js.org/d3-zoom#zoom_transform). The _k_ scale factor may be specified either as a number or a function that returns a number; similarly the _p_ point may be specified either as a two-element array \[ _px_, _py_\] or a function. 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.

## _zoom_.constrain( _constrain_) [​](https://d3js.org/d3-zoom\#zoom_constrain)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _constrain_ is specified, sets the transform constraint function to the specified function and returns the zoom behavior. If _constrain_ is not specified, returns the current constraint function, which defaults to:

js

```
function constrain(transform, extent, translateExtent) {
  var dx0 = transform.invertX(extent[0][0]) - translateExtent[0][0],
      dx1 = transform.invertX(extent[1][0]) - translateExtent[1][0],
      dy0 = transform.invertY(extent[0][1]) - translateExtent[0][1],
      dy1 = transform.invertY(extent[1][1]) - translateExtent[1][1];
  return transform.translate(
    dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1),
    dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1)
  );
}
```

The constraint function must return a \[ _transform_\]#zoomTransform) given the current _transform_, [viewport extent](https://d3js.org/d3-zoom#zoom_extent) and [translate extent](https://d3js.org/d3-zoom#zoom_translateExtent). The default implementation attempts to ensure that the viewport extent does not go outside the translate extent.

## _zoom_.filter( _filter_) [​](https://d3js.org/d3-zoom\#zoom_filter)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _filter_ is specified, sets the filter to the specified function and returns the zoom behavior. If _filter_ is not specified, returns the current filter, which defaults to:

js

```
function filter(event) {
  return (!event.ctrlKey || event.type === 'wheel') && !event.button;
}
```

The filter is passed the current event ( `event`) and datum `d`, with the `this` context as the current DOM element. If the filter returns falsey, the initiating event is ignored and no zoom gestures are 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.

## _zoom_.touchable( _touchable_) [​](https://d3js.org/d3-zoom\#zoom_touchable)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _touchable_ is specified, sets the touch support detector to the specified function and returns the zoom behavior. If _touchable_ is not specified, returns the current touch support detector, which defaults to:

js

```
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 zoom behavior is [applied](https://d3js.org/d3-zoom#_zoom). 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.

## _zoom_.wheelDelta( _delta_) [​](https://d3js.org/d3-zoom\#zoom_wheelDelta)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _delta_ is specified, sets the wheel delta function to the specified function and returns the zoom behavior. If _delta_ is not specified, returns the current wheel delta function, which defaults to:

js

```
function wheelDelta(event) {
  return -event.deltaY * (event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 0.002) * (event.ctrlKey ? 10 : 1);
}
```

The value _Δ_ returned by the wheel delta function determines the amount of scaling applied in response to a [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent). The scale factor [_transform_.k](https://d3js.org/d3-zoom#zoomTransform) is multiplied by 2_Δ_; for example, a _Δ_ of +1 doubles the scale factor, _Δ_ of -1 halves the scale factor.

## _zoom_.extent( _extent_) [​](https://d3js.org/d3-zoom\#zoom_extent)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _extent_ is specified, sets the viewport extent to the specified array of points \[\[ _x0_, _y0_\], \[ _x1_, _y1_\]\], where \[ _x0_, _y0_\] is the top-left corner of the viewport and \[ _x1_, _y1_\] is the bottom-right corner of the viewport, and returns this zoom behavior. 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`, with the `this` context as the current DOM element.

If _extent_ is not specified, returns the current extent accessor, which defaults to \[\[0, 0\], \[ _width_, _height_\]\] where _width_ is the [client width](https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth) of the element and _height_ is its [client height](https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight); for SVG elements, the nearest ancestor SVG element’s viewBox, or [width](https://www.w3.org/TR/SVG/struct.html#SVGElementWidthAttribute) and [height](https://www.w3.org/TR/SVG/struct.html#SVGElementHeightAttribute) attributes, are used. Alternatively, consider using [_element_.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).

The viewport extent affects several functions: the center of the viewport remains fixed during changes by [_zoom_.scaleBy](https://d3js.org/d3-zoom#zoom_scaleBy) and [_zoom_.scaleTo](https://d3js.org/d3-zoom#zoom_scaleTo); the viewport center and dimensions affect the path chosen by [interpolateZoom](https://d3js.org/d3-interpolate/zoom#interpolateZoom); and the viewport extent is needed to enforce the optional [translate extent](https://d3js.org/d3-zoom#zoom_translateExtent).

## _zoom_.scaleExtent( _extent_) [​](https://d3js.org/d3-zoom\#zoom_scaleExtent)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _extent_ is specified, sets the scale extent to the specified array of numbers \[ _k0_, _k1_\] where _k0_ is the minimum allowed scale factor and _k1_ is the maximum allowed scale factor, and returns this zoom behavior. If _extent_ is not specified, returns the current scale extent, which defaults to \[0, ∞\]. The scale extent restricts zooming in and out. It is enforced on interaction and when using [_zoom_.scaleBy](https://d3js.org/d3-zoom#zoom_scaleBy), [_zoom_.scaleTo](https://d3js.org/d3-zoom#zoom_scaleTo) and [_zoom_.translateBy](https://d3js.org/d3-zoom#zoom_translateBy); however, it is not enforced when using [_zoom_.transform](https://d3js.org/d3-zoom#zoom_transform) to set the transform explicitly.

If the user tries to zoom by wheeling when already at the corresponding limit of the scale extent, the wheel events will be ignored and not initiate a zoom gesture. This allows the user to scroll down past a zoomable area after zooming in, or to scroll up after zooming out. If you would prefer to always prevent scrolling on wheel input regardless of the scale extent, register a wheel event listener to prevent the browser default behavior:

js

```
selection
    .call(zoom)
    .on("wheel", event => event.preventDefault());
```

## _zoom_.translateExtent( _extent_) [​](https://d3js.org/d3-zoom\#zoom_translateExtent)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _extent_ is specified, sets the translate extent to the specified array of points \[\[ _x0_, _y0_\], \[ _x1_, _y1_\]\], where \[ _x0_, _y0_\] is the top-left corner of the world and \[ _x1_, _y1_\] is the bottom-right corner of the world, and returns this zoom behavior. If _extent_ is not specified, returns the current translate extent, which defaults to \[\[-∞, -∞\], \[+∞, +∞\]\]. The translate extent restricts panning, and may cause translation on zoom out. It is enforced on interaction and when using [_zoom_.scaleBy](https://d3js.org/d3-zoom#zoom_scaleBy), [_zoom_.scaleTo](https://d3js.org/d3-zoom#zoom_scaleTo) and [_zoom_.translateBy](https://d3js.org/d3-zoom#zoom_translateBy); however, it is not enforced when using [_zoom_.transform](https://d3js.org/d3-zoom#zoom_transform) to set the transform explicitly.

## _zoom_.clickDistance( _distance_) [​](https://d3js.org/d3-zoom\#zoom_clickDistance)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _distance_ is specified, sets the maximum distance that the mouse can move between mousedown and mouseup that will trigger a subsequent click event. If at any point between mousedown and mouseup the mouse is greater than or equal to _distance_ from its position on mousedown, the click event following mouseup will be suppressed. If _distance_ is not specified, returns the current distance threshold, which defaults to zero. The distance threshold is measured in client coordinates ( [_event_.clientX](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX) and [_event_.clientY](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY)).

## _zoom_.tapDistance( _distance_) [​](https://d3js.org/d3-zoom\#zoom_tapDistance)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _distance_ is specified, sets the maximum distance that a double-tap gesture can move between first touchstart and second touchend that will trigger a subsequent double-click event. If _distance_ is not specified, returns the current distance threshold, which defaults to 10. The distance threshold is measured in client coordinates ( [_event_.clientX](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX) and [_event_.clientY](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY)).

## _zoom_.duration( _duration_) [​](https://d3js.org/d3-zoom\#zoom_duration)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _duration_ is specified, sets the duration for zoom transitions on double-click and double-tap to the specified number of milliseconds and returns the zoom behavior. If _duration_ is not specified, returns the current duration, which defaults to 250 milliseconds. If the duration is not greater than zero, double-click and -tap trigger instantaneous changes to the zoom transform rather than initiating smooth transitions.

To disable double-click and double-tap transitions, you can remove the zoom behavior’s dblclick event listener after applying the zoom behavior to the selection:

js

```
selection
    .call(zoom)
    .on("dblclick.zoom", null);
```

## _zoom_.interpolate( _interpolate_) [​](https://d3js.org/d3-zoom\#zoom_interpolate)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _interpolate_ is specified, sets the interpolation factory for zoom transitions to the specified function. If _interpolate_ is not specified, returns the current interpolation factory, which defaults to [interpolateZoom](https://d3js.org/d3-interpolate/zoom#interpolateZoom) to implement smooth zooming. To apply direct interpolation between two views, try [interpolate](https://d3js.org/d3-interpolate/value#interpolate) instead.

## _zoom_.on( _typenames_, _listener_) [​](https://d3js.org/d3-zoom\#zoom_on)

[Source](https://github.com/d3/d3-zoom/blob/main/src/zoom.js) · If _listener_ is specified, sets the event _listener_ for the specified _typenames_ and returns the zoom behavior. 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](https://d3js.org/d3-selection/events#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 `zoom.foo` and `zoom.bar`; the name allows multiple listeners to be registered for the same _type_. The _type_ must be one of the following:

- `start` \- after zooming begins (such as on mousedown).
- `zoom` \- after a change to the zoom transform (such as on mousemove).
- `end` \- after zooming ends (such as on mouseup ).

See [_dispatch_.on](https://d3js.org/d3-dispatch#dispatch_on) for more.

## Zoom events [​](https://d3js.org/d3-zoom\#zoom-events)

When a [zoom event listener](https://d3js.org/d3-zoom#zoom_on) is invoked, it receives the current zoom event as a first argument. The _event_ object exposes several fields:

- _event_.target - the associated [zoom behavior](https://d3js.org/d3-zoom#zoom).
- _event_.type - the string “start”, “zoom” or “end”; see [_zoom_.on](https://d3js.org/d3-zoom#zoom_on).
- _event_.transform - the current [zoom transform](https://d3js.org/d3-zoom#zoomTransform).
- _event_.sourceEvent - the underlying input event, such as mousemove or touchmove.

The zoom behavior handles a variety of interaction events:

| Event | Listening Element | Zoom Event | Default Prevented? |
| --- | --- | --- | --- |
| mousedown⁵ | selection | start | no¹ |
| mousemove² | window¹ | zoom | yes |
| mouseup² | window¹ | end | yes |
| dragstart² | window | - | yes |
| selectstart² | window | - | yes |
| click³ | window | - | yes |
| dblclick | selection | _multiple_ ⁶ | yes |
| wheel⁸ | selection | zoom⁷ | yes |
| touchstart | selection | _multiple_ ⁶ | no⁴ |
| touchmove | selection | zoom | yes |
| touchend | selection | end | no⁴ |
| touchcancel | selection | end | no⁴ |

The propagation of all consumed events is [immediately stopped](https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation).

¹ Necessary to capture events outside an iframe; see [d3-drag#9](https://github.com/d3/d3-drag/issues/9).

² Only applies during an active, mouse-based gesture; see [d3-drag#9](https://github.com/d3/d3-drag/issues/9).

³ Only applies immediately after some mouse-based gestures; see [_zoom_.clickDistance](https://d3js.org/d3-zoom#zoom_clickDistance).

⁴ Necessary to allow [click emulation](https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW7) on touch input; see [d3-drag#9](https://github.com/d3/d3-drag/issues/9).

⁵ Ignored if within 500ms of a touch gesture ending; assumes [click emulation](https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW7).

⁶ Double-click and double-tap initiate a transition that emits start, zoom and end events; see [_zoom_.tapDistance](https://d3js.org/d3-zoom#zoom_tapDistance).

⁷ The first wheel event emits a start event; an end event is emitted when no wheel events are received for 150ms.

⁸ Ignored if already at the corresponding limit of the [scale extent](https://d3js.org/d3-zoom#zoom_scaleExtent).

## zoomTransform( _node_) [​](https://d3js.org/d3-zoom\#zoomTransform)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns the current transform for the specified _node_. Note that _node_ should typically be a DOM element, not a _selection_. (A selection may consist of multiple nodes, in different states, and this function only returns a single transform.) If you have a selection, call [_selection_.node](https://d3js.org/d3-selection/control-flow#selection_node) first:

js

```
var transform = d3.zoomTransform(selection.node());
```

In the context of an [event listener](https://d3js.org/d3-selection/events#selection_on), the _node_ is typically the element that received the input event (which should be equal to [_event_.transform](https://d3js.org/d3-zoom#zoom-events)), _this_:

js

```
var transform = d3.zoomTransform(this);
```

Internally, an element’s transform is stored as _element_.\_\_zoom; however, you should use this method rather than accessing it directly. If the given _node_ has no defined transform, returns the transform of the closest ancestor, or if none exists, the [identity transformation](https://d3js.org/d3-zoom#zoomIdentity). The returned transform represents a two-dimensional [transformation matrix](https://en.wikipedia.org/wiki/Transformation_matrix#Affine_transformations) of the form:

_k_ 0 _tx_

0 _k_ _ty_

0 0 1

(This matrix is capable of representing only scale and translation; a future release may also allow rotation, though this would probably not be a backwards-compatible change.) The position ⟨ _x_, _y_⟩ is transformed to ⟨ _xk_ \+ _tx_, _yk_ \+ _ty_⟩. The transform object exposes the following properties:

- _transform_.x - the translation amount _tx_ along the _x_-axis.
- _transform_.y - the translation amount _ty_ along the _y_-axis.
- _transform_.k - the scale factor _k_.

These properties should be considered read-only; instead of mutating a transform, use [_transform_.scale](https://d3js.org/d3-zoom#transform_scale) and [_transform_.translate](https://d3js.org/d3-zoom#transform_translate) to derive a new transform. Also see [_zoom_.scaleBy](https://d3js.org/d3-zoom#zoom_scaleBy), [_zoom_.scaleTo](https://d3js.org/d3-zoom#zoom_scaleTo) and [_zoom_.translateBy](https://d3js.org/d3-zoom#zoom_translateBy) for convenience methods on the zoom behavior. To create a transform with a given _k_, _tx_, and _ty_:

js

```
var t = d3.zoomIdentity.translate(x, y).scale(k);
```

To apply the transformation to a [Canvas 2D context](https://www.w3.org/TR/2dcontext/), use [_context_.translate](https://www.w3.org/TR/2dcontext/#dom-context-2d-translate) followed by [_context_.scale](https://www.w3.org/TR/2dcontext/#dom-context-2d-scale):

js

```
context.translate(transform.x, transform.y);
context.scale(transform.k, transform.k);
```

Similarly, to apply the transformation to HTML elements via [CSS](https://www.w3.org/TR/css-transforms-1/):

js

```
div.style("transform", "translate(" + transform.x + "px," + transform.y + "px) scale(" + transform.k + ")");
div.style("transform-origin", "0 0");
```

To apply the transformation to [SVG](https://www.w3.org/TR/SVG/coords.html#TransformAttribute):

js

```
g.attr("transform", "translate(" + transform.x + "," + transform.y + ") scale(" + transform.k + ")");
```

Or more simply, taking advantage of [_transform_.toString](https://d3js.org/d3-zoom#transform_toString):

js

```
g.attr("transform", transform);
```

Note that the order of transformations matters! The translate must be applied before the scale.

## zoomIdentity [​](https://d3js.org/d3-zoom\#zoomIdentity)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · The identity transform, where _k_ = 1, _tx_ = _ty_ = 0.

## new d3.ZoomTransform( _k_, _x_, _y_) [​](https://d3js.org/d3-zoom\#ZoomTransform)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns a transform with scale _k_ and translation ( _x_, _y_).

## _transform_.scale( _k_) [​](https://d3js.org/d3-zoom\#transform_scale)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns a transform whose scale _k₁_ is equal to _k₀k_, where _k₀_ is this transform’s scale.

## _transform_.translate( _x_, _y_) [​](https://d3js.org/d3-zoom\#transform_translate)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns a transform whose translation _tx1_ and _ty1_ is equal to _tx0_ \+ _tk x_ and _ty0_ \+ _tk y_, where _tx0_ and _ty0_ is this transform’s translation and _tk_ is this transform’s scale.

## _transform_.apply( _point_) [​](https://d3js.org/d3-zoom\#transform_apply)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns the transformation of the specified _point_ which is a two-element array of numbers \[ _x_, _y_\]. The returned point is equal to \[ _xk_ \+ _tx_, _yk_ \+ _ty_\].

## _transform_.applyX( _x_) [​](https://d3js.org/d3-zoom\#transform_applyX)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns the transformation of the specified _x_-coordinate, _xk_ \+ _tx_.

## _transform_.applyY( _y_) [​](https://d3js.org/d3-zoom\#transform_applyY)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns the transformation of the specified y coordinate, _yk_ \+ _ty_.

## _transform_.invert( _point_) [​](https://d3js.org/d3-zoom\#transform_invert)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns the inverse transformation of the specified _point_ which is a two-element array of numbers \[ _x_, _y_\]. The returned point is equal to \[( _x_ \- _tx_) / _k_, ( _y_ \- _ty_) / _k_\].

## _transform_.invertX( _x_) [​](https://d3js.org/d3-zoom\#transform_invertX)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns the inverse transformation of the specified _x_-coordinate, ( _x_ \- _tx_) / _k_.

## _transform_.invertY( _y_) [​](https://d3js.org/d3-zoom\#transform_invertY)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns the inverse transformation of the specified y coordinate, ( _y_ \- _ty_) / _k_.

## _transform_.rescaleX( _x_) [​](https://d3js.org/d3-zoom\#transform_rescaleX)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns a [copy](https://d3js.org/d3-scale/linear#linear_copy) of the [continuous scale](https://d3js.org/d3-scale/linear) _x_ whose [domain](https://d3js.org/d3-scale/linear#linear_domain) is transformed. This is implemented by first applying the [inverse _x_-transform](https://d3js.org/d3-zoom#transform_invertX) on the scale’s [range](https://d3js.org/d3-scale/linear#linear_range), and then applying the [inverse scale](https://d3js.org/d3-scale/linear#linear_invert) to compute the corresponding domain:

js

```
function rescaleX(x) {
  var range = x.range().map(transform.invertX, transform),
      domain = range.map(x.invert, x);
  return x.copy().domain(domain);
}
```

The scale _x_ must use [interpolateNumber](https://d3js.org/d3-interpolate/value#interpolateNumber); do not use [_continuous_.rangeRound](https://d3js.org/d3-scale/linear#linear_rangeRound) as this reduces the accuracy of [_continuous_.invert](https://d3js.org/d3-scale/linear#linear_invert) and can lead to an inaccurate rescaled domain. This method does not modify the input scale _x_; _x_ thus represents the untransformed scale, while the returned scale represents its transformed view.

## _transform_.rescaleY( _y_) [​](https://d3js.org/d3-zoom\#transform_rescaleY)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns a [copy](https://d3js.org/d3-scale/linear#linear_copy) of the [continuous scale](https://d3js.org/d3-scale/linear) _y_ whose [domain](https://d3js.org/d3-scale/linear#linear_domain) is transformed. This is implemented by first applying the [inverse _y_-transform](https://d3js.org/d3-zoom#transform_invertY) on the scale’s [range](https://d3js.org/d3-scale/linear#linear_range), and then applying the [inverse scale](https://d3js.org/d3-scale/linear#linear_invert) to compute the corresponding domain:

js

```
function rescaleY(y) {
  var range = y.range().map(transform.invertY, transform),
      domain = range.map(y.invert, y);
  return y.copy().domain(domain);
}
```

The scale _y_ must use [interpolateNumber](https://d3js.org/d3-interpolate/value#interpolateNumber); do not use [_continuous_.rangeRound](https://d3js.org/d3-scale/linear#linear_rangeRound) as this reduces the accuracy of [_continuous_.invert](https://d3js.org/d3-scale/linear#linear_invert) and can lead to an inaccurate rescaled domain. This method does not modify the input scale _y_; _y_ thus represents the untransformed scale, while the returned scale represents its transformed view.

## _transform_.toString() [​](https://d3js.org/d3-zoom\#transform_toString)

[Source](https://github.com/d3/d3-zoom/blob/main/src/transform.js) · Returns a string representing the [SVG transform](https://www.w3.org/TR/SVG/coords.html#TransformAttribute) corresponding to this transform. Implemented as:

js

```
function toString() {
  return "translate(" + this.x + "," + this.y + ") scale(" + this.k + ")";
}
```

## Categorical Color Schemes
[Skip to content](https://d3js.org/d3-scale-chromatic/categorical#VPContent)

On this page

# Categorical schemes [​](https://d3js.org/d3-scale-chromatic/categorical\#categorical-schemes)

For example, to create a categorical color scale using the [Accent](https://d3js.org/d3-scale-chromatic/categorical#schemeAccent) color scheme:

js

```
const color = d3.scaleOrdinal(d3.schemeAccent);
```

## schemeCategory10 [​](https://d3js.org/d3-scale-chromatic/categorical\#schemeCategory10)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/category10.js) · An array of ten categorical colors represented as RGB hexadecimal strings.

## schemeAccent [​](https://d3js.org/d3-scale-chromatic/categorical\#schemeAccent)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/Accent.js) · An array of eight categorical colors represented as RGB hexadecimal strings.

## schemeDark2 [​](https://d3js.org/d3-scale-chromatic/categorical\#schemeDark2)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/Dark2.js) · An array of eight categorical colors represented as RGB hexadecimal strings.

## schemeObservable10 [​](https://d3js.org/d3-scale-chromatic/categorical\#schemeObservable10)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/observable10.js) · An array of ten categorical colors represented as RGB hexadecimal strings.

## schemePaired [​](https://d3js.org/d3-scale-chromatic/categorical\#schemePaired)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/Paired.js) · An array of twelve categorical colors represented as RGB hexadecimal strings.

## schemePastel1 [​](https://d3js.org/d3-scale-chromatic/categorical\#schemePastel1)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/Pastel1.js) · An array of nine categorical colors represented as RGB hexadecimal strings.

## schemePastel2 [​](https://d3js.org/d3-scale-chromatic/categorical\#schemePastel2)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/Pastel2.js) · An array of eight categorical colors represented as RGB hexadecimal strings.

## schemeSet1 [​](https://d3js.org/d3-scale-chromatic/categorical\#schemeSet1)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/Set1.js) · An array of nine categorical colors represented as RGB hexadecimal strings.

## schemeSet2 [​](https://d3js.org/d3-scale-chromatic/categorical\#schemeSet2)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/Set2.js) · An array of eight categorical colors represented as RGB hexadecimal strings.

## schemeSet3 [​](https://d3js.org/d3-scale-chromatic/categorical\#schemeSet3)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/Set3.js) · An array of twelve categorical colors represented as RGB hexadecimal strings.

## schemeTableau10 [​](https://d3js.org/d3-scale-chromatic/categorical\#schemeTableau10)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/Tableau10.js) · An array of ten categorical colors authored by Tableau as part of [Tableau 10](https://www.tableau.com/about/blog/2016/7/colors-upgrade-tableau-10-56782) represented as RGB hexadecimal strings.

## D3 Selection Guide
[Skip to content](https://d3js.org/d3-selection#VPContent)

Return to top

# d3-selection [​](https://d3js.org/d3-selection\#d3-selection)

Selections allow powerful data-driven transformation of the document object model (DOM): set [attributes](https://d3js.org/d3-selection/modifying#selection_attr), [styles](https://d3js.org/d3-selection/modifying#selection_style), [properties](https://d3js.org/d3-selection/modifying#selection_property), [HTML](https://d3js.org/d3-selection/modifying#selection_html) or [text](https://d3js.org/d3-selection/modifying#selection_text) content, and more. Using the [data join](https://d3js.org/d3-selection/joining)’s [enter](https://d3js.org/d3-selection/joining#selection_enter) and [exit](https://d3js.org/d3-selection/joining#selection_enter) selections, you can also [add](https://d3js.org/d3-selection/modifying#selection_append) or [remove](https://d3js.org/d3-selection/modifying#selection_remove) elements to correspond to data.

See one of:

- [Selecting elements](https://d3js.org/d3-selection/selecting) \- querying for DOM elements.
- [Modifying elements](https://d3js.org/d3-selection/modifying) \- modifying attributes of selected elements.
- [Joining data](https://d3js.org/d3-selection/joining) \- joining data to selected elements for visualization.
- [Handling events](https://d3js.org/d3-selection/events) \- declaring event listeners for interaction.
- [Control flow](https://d3js.org/d3-selection/control-flow) \- iterating over selected elements.
- [Local variables](https://d3js.org/d3-selection/locals) \- attaching state to elements.
- [Namespaces](https://d3js.org/d3-selection/namespaces) \- dealing with XML namespaces.

For more, see [the d3-selection collection on Observable](https://observablehq.com/collection/@d3/d3-selection).

## D3.js Sequential Scales
[Skip to content](https://d3js.org/d3-scale/sequential#VPContent)

On this page

# Sequential scales [​](https://d3js.org/d3-scale/sequential\#sequential-scales)

Sequential scales are similar to [linear scales](https://d3js.org/d3-scale/linear) in that they map a continuous, numeric input domain to a continuous output range. Unlike linear scales, the input domain and output range of a sequential scale always have exactly two elements, and the output range is typically specified as an interpolator rather than an array of values. Sequential scales are typically used for a color encoding; see also [d3-scale-chromatic](https://d3js.org/d3-scale-chromatic). These scales do not expose [invert](https://d3js.org/d3-scale/linear#linear_invert) and [interpolate](https://d3js.org/d3-scale/linear#linear_interpolate) methods. There are also [log](https://d3js.org/d3-scale/sequential#scaleSequentialLog), [pow](https://d3js.org/d3-scale/sequential#scaleSequentialPow), [symlog](https://d3js.org/d3-scale/sequential#scaleSequentialSymlog), and [quantile](https://d3js.org/d3-scale/sequential#scaleSequentialQuantile) variants of sequential scales.

## scaleSequential( _domain_, _interpolator_) [​](https://d3js.org/d3-scale/sequential\#scaleSequential)

[Examples](https://observablehq.com/@d3/sequential-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/sequential.js) · Constructs a new sequential scale with the specified _domain_ and [_interpolator_](https://d3js.org/d3-scale/sequential#sequential_interpolator) function or array.

js

```
const color = d3.scaleSequential([0, 100], d3.interpolateBlues);
```

If _domain_ is not specified, it defaults to \[0, 1\].

js

```
const color = d3.scaleSequential(d3.interpolateBlues);
```

If _interpolator_ is not specified, it defaults to the identity function.

js

```
const identity = d3.scaleSequential();
```

When the scale is applied, the interpolator will be invoked with a value typically in the range \[0, 1\], where 0 represents the minimum value and 1 represents the maximum value. For example, to implement the ill-advised angry rainbow scale (please use [interpolateRainbow](https://d3js.org/d3-scale-chromatic/cyclical#interpolateRainbow) instead):

js

```
const rainbow = d3.scaleSequential((t) => d3.hsl(t * 360, 1, 0.5) + "");
```

If _interpolator_ is an array, it represents the scale’s two-element output range and is converted to an interpolator function using [interpolate](https://d3js.org/d3-interpolate/value#interpolate).

js

```
const color = d3.scaleSequential(["red", "blue"]);
```

A sequential scale’s domain must be numeric and must contain exactly two values.

## _sequential_.interpolator( _interpolator_) [​](https://d3js.org/d3-scale/sequential\#sequential_interpolator)

If _interpolator_ is specified, sets the scale’s interpolator to the specified function.

js

```
const color = d3.scaleSequential().interpolator(d3.interpolateBlues);
```

If _interpolator_ is not specified, returns the scale’s current interpolator.

js

```
color.interpolator() // d3.interpolateBlues
```

## _sequential_.range( _range_) [​](https://d3js.org/d3-scale/sequential\#sequential_range)

See [_linear_.range](https://d3js.org/d3-scale/linear#linear_range). If _range_ is specified, the given two-element array is converted to an interpolator function using [interpolate](https://d3js.org/d3-interpolate/value#interpolate).

js

```
const color = d3.scaleSequential().range(["red", "blue"]);
```

The above is equivalent to:

js

```
const color = d3.scaleSequential(d3.interpolate("red", "blue"));
```

## _sequential_.rangeRound( _range_) [​](https://d3js.org/d3-scale/sequential\#sequential_rangeRound)

See [_linear_.rangeRound](https://d3js.org/d3-scale/linear#linear_rangeRound). If _range_ is specified, implicitly uses [interpolateRound](https://d3js.org/d3-interpolate/value#interpolateRound) as the interpolator.

## scaleSequentialLog( _domain_, _range_) [​](https://d3js.org/d3-scale/sequential\#scaleSequentialLog)

Returns a new sequential scale with a logarithmic transform, analogous to a [log scale](https://d3js.org/d3-scale/log).

## scaleSequentialPow( _domain_, _range_) [​](https://d3js.org/d3-scale/sequential\#scaleSequentialPow)

Returns a new sequential scale with an exponential transform, analogous to a [power scale](https://d3js.org/d3-scale/pow).

## scaleSequentialSqrt( _domain_, _range_) [​](https://d3js.org/d3-scale/sequential\#scaleSequentialSqrt)

Returns a new sequential scale with a square-root transform, analogous to a [sqrt scale](https://d3js.org/d3-scale/pow#scaleSqrt).

## scaleSequentialSymlog( _domain_, _range_) [​](https://d3js.org/d3-scale/sequential\#scaleSequentialSymlog)

Returns a new sequential scale with a symmetric logarithmic transform, analogous to a [symlog scale](https://d3js.org/d3-scale/symlog).

## scaleSequentialQuantile( _domain_, _range_) [​](https://d3js.org/d3-scale/sequential\#scaleSequentialQuantile)

[Source](https://github.com/d3/d3-scale/blob/main/src/sequentialQuantile.js) · Returns a new sequential scale with a _p_-quantile transform, analogous to a [quantile scale](https://d3js.org/d3-scale/quantile).

## _sequentialQuantile_.quantiles( _n_) [​](https://d3js.org/d3-scale/sequential\#sequentialQuantile_quantiles)

[Source](https://github.com/d3/d3-scale/blob/main/src/sequentialQuantile.js) · Returns an array of _n_ \+ 1 quantiles.

js

```
const color = d3.scaleSequentialQuantile()
    .domain(penguins.map((d) => d.body_mass_g))
    .interpolator(d3.interpolateBlues);

color.quantiles(4); // [2700, 3550, 4050, 4750, 6300]
```

For example, if _n_ = 4, returns an array of five numbers: the minimum value, the first quartile, the median, the third quartile, and the maximum.

## D3.js Event Handling
[Skip to content](https://d3js.org/d3-selection/events#VPContent)

On this page

# Handling events [​](https://d3js.org/d3-selection/events\#handling-events)

For interaction, selections allow listening for and dispatching of events.

## _selection_.on( _typenames_, _listener_, _options_) [​](https://d3js.org/d3-selection/events\#selection_on)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/on.js) · Adds or removes a _listener_ to each selected element for the specified event _typenames_.

js

```
d3.selectAll("p").on("click", (event) => console.log(event))
```

The _typenames_ is a string event type, such as `click`, `mouseover`, or `submit`; any [DOM event type](https://developer.mozilla.org/en-US/docs/Web/Events#Standard_events) supported by your browser may be used. The type may be optionally followed by a period ( `.`) and a name; the optional name allows multiple callbacks to be registered to receive events of the same type, such as `click.foo` and `click.bar`. To specify multiple typenames, separate typenames with spaces, such as `input change` or `click.foo click.bar`.

When a specified event is dispatched on a selected element, the specified _listener_ will be evaluated for the element, being passed the current event ( _event_) and the current datum ( _d_), with _this_ as the current DOM element ( _event_.currentTarget). Listeners always see the latest datum for their element. Note: while you can use [_event_.pageX](https://developer.mozilla.org/en/DOM/event.pageX) and [_event_.pageY](https://developer.mozilla.org/en/DOM/event.pageY) directly, it is often convenient to transform the event position to the local coordinate system of the element that received the event using [d3.pointer](https://d3js.org/d3-selection/events#pointer).

If an event listener was previously registered for the same _typename_ on a selected element, the old listener is removed before the new listener is added. To remove a listener, pass null as the _listener_. To remove all listeners for a given name, pass null as the _listener_ and `.foo` as the _typename_, where `foo` is the name; to remove all listeners with no name, specify `.` as the _typename_.

An optional _options_ object may specify characteristics about the event listener, such as whether it is capturing or passive; see [_element_.addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener).

If a _listener_ is not specified, returns the currently-assigned listener for the specified event _typename_ on the first (non-null) selected element, if any. If multiple typenames are specified, the first matching listener is returned.

## _selection_.dispatch( _type_, _parameters_) [​](https://d3js.org/d3-selection/events\#selection_dispatch)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/dispatch.js) · Dispatches a [custom event](http://www.w3.org/TR/dom/#interface-customevent) of the specified _type_ to each selected element, in order.

js

```
d3.select("p").dispatch("click")
```

An optional _parameters_ object may be specified to set additional properties of the event. It may contain the following fields:

- [`bubbles`](https://www.w3.org/TR/dom/#dom-event-bubbles) \- if true, the event is dispatched to ancestors in reverse tree order.
- [`cancelable`](https://www.w3.org/TR/dom/#dom-event-cancelable) \- if true, _event_.preventDefault is allowed.
- [`detail`](https://www.w3.org/TR/dom/#dom-customevent-detail) \- any custom data associated with the event.

If _parameters_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). It must return the parameters for the current element.

## pointer( _event_, _target_) [​](https://d3js.org/d3-selection/events\#pointer)

[Source](https://github.com/d3/d3-selection/blob/main/src/pointer.js) · Returns a two-element array of numbers \[ _x_, _y_\] representing the coordinates of the specified _event_ relative to the specified _target_.

js

```
const [x, y] = d3.pointer(event);
```

_event_ can be a [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent), a [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent), a [Touch](https://www.w3.org/TR/touch-events/#touch-interface), or a custom event holding a UIEvent as _event_.sourceEvent.

If _target_ is not specified, it defaults to the source event’s currentTarget property, if available. If the _target_ is an SVG element, the event’s coordinates are transformed using the [inverse](https://www.w3.org/TR/geometry-1/#dom-dommatrixreadonly-inverse) of the [screen coordinate transformation matrix](https://www.w3.org/TR/SVG/types.html#__svg__SVGGraphicsElement__getScreenCTM). If the _target_ is an HTML element, the event’s coordinates are translated relative to the top-left corner of the _target_’s [bounding client rectangle](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). (As such, the coordinate system can only be translated relative to the client coordinates. See also [GeometryUtils](https://www.w3.org/TR/cssom-view-1/#the-geometryutils-interface).) Otherwise, \[ _event_.pageX, _event_.pageY\] is returned.

## pointers( _event_, _target_) [​](https://d3js.org/d3-selection/events\#pointers)

[Source](https://github.com/d3/d3-selection/blob/main/src/pointers.js) · Returns an array \[\[ _x0_, _y0_\], \[ _x1_, _y1_\]…\] of coordinates of the specified _event_’s pointer locations relative to the specified _target_.

js

```
const points = d3.pointers(event);
```

For touch events, the returned array of positions corresponds to the _event_.touches array; for other events, returns a single-element array.

If _target_ is not specified, it defaults to the source event’s currentTarget property, if any.

## Hierarchical Data Visualization
[Skip to content](https://d3js.org/d3-hierarchy#VPContent)

Return to top

# d3-hierarchy [​](https://d3js.org/d3-hierarchy\#d3-hierarchy)

Many datasets are intrinsically hierarchical: [geographic entities](https://www.census.gov/programs-surveys/geography/guidance/hierarchy.html), such as census blocks, census tracts, counties and states; the command structure of businesses and governments; file systems; software packages. And even non-hierarchical data may be arranged hierarchically as with [_k_-means clustering](https://en.wikipedia.org/wiki/K-means_clustering) or [phylogenetic trees](https://observablehq.com/@d3/tree-of-life). A good hierarchical visualization facilitates rapid multiscale inference: micro-observations of individual elements and macro-observations of large groups.

This module implements several popular techniques for visualizing hierarchical data:

**Node-link diagrams** show topology using discrete marks for nodes and links, such as a circle for each node and a line connecting each parent and child. The [“tidy” tree](https://d3js.org/d3-hierarchy/tree) is delightfully compact, while the [dendrogram](https://d3js.org/d3-hierarchy/cluster) places leaves at the same level. (These have both polar and Cartesian forms.) [Indented trees](https://observablehq.com/@d3/indented-tree) are useful for interactive browsing.

**Adjacency diagrams** show topology through the relative placement of nodes. They may also encode a quantitative dimension in the area of each node, for example to show revenue or file size. The [“icicle” diagram](https://d3js.org/d3-hierarchy/partition) uses rectangles, while the “sunburst” uses annular segments.

**Enclosure diagrams** also use an area encoding, but show topology through containment. A [treemap](https://d3js.org/d3-hierarchy/treemap) recursively subdivides area into rectangles. [Circle-packing](https://d3js.org/d3-hierarchy/pack) tightly nests circles; this is not as space-efficient as a treemap, but perhaps more readily shows topology.

See one of:

- [Hierarchies](https://d3js.org/d3-hierarchy/hierarchy) \- represent and manipulate hierarchical data
- [Stratify](https://d3js.org/d3-hierarchy/stratify) \- organize tabular data into a [hierarchy](https://d3js.org/d3-hierarchy/hierarchy)
- [Tree](https://d3js.org/d3-hierarchy/tree) \- construct “tidy” tree diagrams of hierarchies
- [Cluster](https://d3js.org/d3-hierarchy/cluster) \- construct tree diagrams that place leaf nodes at the same depth
- [Partition](https://d3js.org/d3-hierarchy/partition) \- construct space-filling adjacency diagrams
- [Pack](https://d3js.org/d3-hierarchy/pack) \- construct enclosure diagrams by tightly nesting circles
- [Treemap](https://d3js.org/d3-hierarchy/treemap) \- recursively subdivide rectangles by quantitative value

## D3.js Symbol Generator
[Skip to content](https://d3js.org/d3-shape/symbol#VPContent)

On this page

# Symbols [​](https://d3js.org/d3-shape/symbol\#symbols)

[Examples](https://observablehq.com/@d3/fitted-symbols) · Symbols provide a categorical shape encoding as in a scatterplot. Symbols are centered at the origin; use a [transform](http://www.w3.org/TR/SVG/coords.html#TransformAttribute) to move the symbol to a different position.

## symbol( _type_, _size_) [​](https://d3js.org/d3-shape/symbol\#symbol)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol.js) · Constructs a new symbol generator of the specified [type](https://d3js.org/d3-shape/symbol#symbol_type) and [size](https://d3js.org/d3-shape/symbol#symbol_size). If not specified, _type_ defaults to a circle, and _size_ defaults to 64.

js

```
svg.append("path").attr("d", d3.symbol(d3.symbolCross));
```

## _symbol_(... _arguments_) [​](https://d3js.org/d3-shape/symbol\#_symbol)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol.js) · Generates a symbol for the given _arguments_. The _arguments_ are arbitrary; they are propagated to the symbol generator’s accessor functions along with the `this` object. With the default settings, invoking the symbol generator produces a circle of 64 square pixels.

js

```
d3.symbol()() // "M4.514,0A4.514,4.514,0,1,1,-4.514,0A4.514,4.514,0,1,1,4.514,0"
```

If the symbol generator has a [context](https://d3js.org/d3-shape/symbol#symbol_context), then the symbol is rendered to this context as a sequence of [path method](http://www.w3.org/TR/2dcontext/#canvaspathmethods) calls and this function returns void. Otherwise, a [path data](http://www.w3.org/TR/SVG/paths.html#PathData) string is returned.

## _symbol_.type( _type_) [​](https://d3js.org/d3-shape/symbol\#symbol_type)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol.js) · If _type_ is specified, sets the symbol type to the specified function or symbol type and returns this symbol generator.

js

```
const symbol = d3.symbol().type(d3.symbolCross);
```

If _type_ is a function, the symbol generator’s arguments and _this_ are passed through. This is convenient for use with [_selection_.attr](https://d3js.org/d3-selection/modifying#selection_attr), say in conjunction with an [ordinal scale](https://d3js.org/d3-scale/ordinal) to produce a categorical symbol encoding.

js

```
const symbolType = d3.scaleOrdinal(d3.symbolsFill);
const symbol = d3.symbol().type((d) => symbolType(d.category));
```

If _type_ is not specified, returns the current symbol type accessor.

js

```
symbol.type() // () => d3.symbolCross
```

The symbol type accessor defaults to:

js

```
function type() {
  return circle;
}
```

See [symbolsFill](https://d3js.org/d3-shape/symbol#symbolsFill) and [symbolsStroke](https://d3js.org/d3-shape/symbol#symbolsStroke) for built-in symbol types. To implement a custom symbol type, pass an object that implements [_symbolType_.draw](https://d3js.org/d3-shape/symbol#symbolType_draw).

## _symbol_.size( _size_) [​](https://d3js.org/d3-shape/symbol\#symbol_size)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol.js) · If _size_ is specified, sets the size to the specified function or number and returns this symbol generator.

js

```
const symbol = d3.symbol().size(100);
```

If _size_ is a function, the symbol generator’s arguments and _this_ are passed through. This is convenient for use with [_selection_.attr](https://d3js.org/d3-selection/modifying#selection_attr), say in conjunction with a [linear scale](https://d3js.org/d3-scale/linear) to produce a quantitative size encoding.

js

```
const symbolSize = d3.scaleLinear([0, 100]);
const symbol = d3.symbol().size((d) => symbolSize(d.value));
```

If _size_ is not specified, returns the current size accessor.

js

```
symbol.size() // () => 100
```

The size accessor defaults to:

js

```
function size() {
  return 64;
}
```

## _symbol_.context( _context_) [​](https://d3js.org/d3-shape/symbol\#symbol_context)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol.js) · If _context_ is specified, sets the context and returns this symbol generator.

js

```
const context = canvas.getContext("2d");
const symbol = d3.symbol().context(context);
```

If _context_ is not specified, returns the current context.

js

```
symbol.context() // context
```

The context defaults to null. If the context is not null, then the [generated symbol](https://d3js.org/d3-shape/symbol#_symbol) is rendered to this context as a sequence of [path method](http://www.w3.org/TR/2dcontext/#canvaspathmethods) calls. Otherwise, a [path data](http://www.w3.org/TR/SVG/paths.html#PathData) string representing the generated symbol is returned.

## _symbol_.digits( _digits_) [​](https://d3js.org/d3-shape/symbol\#symbol_digits)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol.js) · If _digits_ is specified, sets the maximum number of digits after the decimal separator and returns this symbol generator.

js

```
const symbol = d3.symbol().digits(3);
```

If _digits_ is not specified, returns the current maximum fraction digits, which defaults to 3.

js

```
symbol.digits() // 3
```

This option only applies when the associated [_context_](https://d3js.org/d3-shape/symbol#symbol_context) is null, as when this symbol generator is used to produce [path data](http://www.w3.org/TR/SVG/paths.html#PathData).

## symbolsFill [​](https://d3js.org/d3-shape/symbol\#symbolsFill)

circlecrossdiamondsquarestartrianglewye

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol.js) · An array containing a set of symbol types designed for filling: [circle](https://d3js.org/d3-shape/symbol#symbolCircle), [cross](https://d3js.org/d3-shape/symbol#symbolCross), [diamond](https://d3js.org/d3-shape/symbol#symbolDiamond), [square](https://d3js.org/d3-shape/symbol#symbolSquare), [star](https://d3js.org/d3-shape/symbol#symbolStar), [triangle](https://d3js.org/d3-shape/symbol#symbolTriangle), and [wye](https://d3js.org/d3-shape/symbol#symbolWye). Useful for a categorical shape encoding with an [ordinal scale](https://d3js.org/d3-scale/ordinal).

js

```
const symbolType = d3.scaleOrdinal(d3.symbolsFill);
```

## symbolsStroke [​](https://d3js.org/d3-shape/symbol\#symbolsStroke)

asteriskcirclediamond2plussquare2timestriangle2

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol.js) · An array containing a set of symbol types designed for stroking: [circle](https://d3js.org/d3-shape/symbol#symbolCircle), [plus](https://d3js.org/d3-shape/symbol#symbolPlus), [times](https://d3js.org/d3-shape/symbol#symbolTimes), [triangle2](https://d3js.org/d3-shape/symbol#symbolTriangle2), [asterisk](https://d3js.org/d3-shape/symbol#symbolAsterisk), [square2](https://d3js.org/d3-shape/symbol#symbolSquare2), and [diamond2](https://d3js.org/d3-shape/symbol#symbolDiamond2). Useful for a categorical shape encoding with an [ordinal scale](https://d3js.org/d3-scale/ordinal).

js

```
const symbolType = d3.scaleOrdinal(d3.symbolsStroke);
```

## symbolAsterisk [​](https://d3js.org/d3-shape/symbol\#symbolAsterisk)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/asterisk.js) · The asterisk symbol type; intended for stroking.

## symbolCircle [​](https://d3js.org/d3-shape/symbol\#symbolCircle)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/circle.js) · The circle symbol type; intended for either filling or stroking.

## symbolCross [​](https://d3js.org/d3-shape/symbol\#symbolCross)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/cross.js) · The Greek cross symbol type, with arms of equal length; intended for filling.

## symbolDiamond [​](https://d3js.org/d3-shape/symbol\#symbolDiamond)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/diamond.js) · The rhombus symbol type; intended for filling.

## symbolDiamond2 [​](https://d3js.org/d3-shape/symbol\#symbolDiamond2)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/diamond.js) · The rotated square symbol type; intended for stroking.

## symbolPlus [​](https://d3js.org/d3-shape/symbol\#symbolPlus)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/plus.js) · The plus symbol type; intended for stroking.

## symbolSquare [​](https://d3js.org/d3-shape/symbol\#symbolSquare)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/square.js) · The square symbol type; intended for filling.

## symbolSquare2 [​](https://d3js.org/d3-shape/symbol\#symbolSquare2)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/square2.js) · The square2 symbol type; intended for stroking.

## symbolStar [​](https://d3js.org/d3-shape/symbol\#symbolStar)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/star.js) · The pentagonal star (pentagram) symbol type; intended for filling.

## symbolTriangle [​](https://d3js.org/d3-shape/symbol\#symbolTriangle)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/triangle.js) · The up-pointing triangle symbol type; intended for filling.

## symbolTriangle2 [​](https://d3js.org/d3-shape/symbol\#symbolTriangle2)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/triangle2.js) · The up-pointing triangle symbol type; intended for stroking.

## symbolWye [​](https://d3js.org/d3-shape/symbol\#symbolWye)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/wye.js) · The Y-shape symbol type; intended for filling.

## symbolTimes [​](https://d3js.org/d3-shape/symbol\#symbolTimes)

[Source](https://github.com/d3/d3-shape/blob/main/src/symbol/times.js) · The X-shape symbol type; intended for stroking.

## Custom symbols [​](https://d3js.org/d3-shape/symbol\#custom-symbols)

Symbol types are typically not used directly, instead being passed to [_symbol_.type](https://d3js.org/d3-shape/symbol#symbol_type). However, you can define your own symbol type implementation should none of the built-in types satisfy your needs using the following interface. You can also use this low-level interface with a built-in symbol type as an alternative to the symbol generator.

js

```
const path = d3.pathRound(3);
const circle = d3.symbolCircle.draw(path, 64);
path.toString(); // "M4.514,0A4.514,4.514,0,1,1,-4.514,0A4.514,4.514,0,1,1,4.514,0"
```

### _symbolType_.draw( _context_, _size_) [​](https://d3js.org/d3-shape/symbol\#symbolType_draw)

Renders this symbol type to the specified _context_ with the specified _size_ in square pixels. The _context_ implements the [CanvasPathMethods](http://www.w3.org/TR/2dcontext/#canvaspathmethods) interface. (Note that this is a subset of the CanvasRenderingContext2D interface!) See also [d3-path](https://d3js.org/d3-path).

## pointRadial( _angle_, _radius_) [​](https://d3js.org/d3-shape/symbol\#pointRadial)

[Examples](https://observablehq.com/@d3/radial-area-chart) · [Source](https://github.com/d3/d3-shape/blob/main/src/pointRadial.js) · Returns the point \[ _x_, _y_\] for the given _angle_ in radians, with 0 at - _y_ (12 o’clock) and positive angles proceeding clockwise, and the given _radius_.

js

```
d3.pointRadial(Math.PI / 3, 100) // [86.60254037844386, -50]
```

## D3.js Shape Generators
[Skip to content](https://d3js.org/d3-shape#VPContent)

Return to top

# d3-shape [​](https://d3js.org/d3-shape\#d3-shape)

Visualizations can be represented by discrete graphical marks such as [symbols](https://d3js.org/d3-shape/symbol), [arcs](https://d3js.org/d3-shape/arc), [lines](https://d3js.org/d3-shape/line), and [areas](https://d3js.org/d3-shape/area). While the rectangles of a bar chart may sometimes be simple, other shapes are complex, such as rounded annular sectors and Catmull–Rom splines. The d3-shape module provides a variety of shape generators for your convenience.

As with other aspects of D3, these shapes are driven by data: each shape generator exposes accessors that control how the input data are mapped to a visual representation. For example, you might define a line generator for a time series by [scaling](https://d3js.org/d3-scale) fields of your data to fit the chart:

js

```
const line = d3.line()
    .x((d) => x(d.date))
    .y((d) => y(d.value));
```

This line generator can then be used to compute the `d` attribute of an SVG path element:

js

```
path.datum(data).attr("d", line);
```

Or you can use it to render to a Canvas 2D context:

js

```
line.context(context)(data);
```

See one of:

- [Arcs](https://d3js.org/d3-shape/arc) \- circular or annular sectors, as in a pie or donut chart.
- [Areas](https://d3js.org/d3-shape/area) \- an area defined by a bounding topline and baseline, as in an area chart.
- [Curves](https://d3js.org/d3-shape/curve) \- interpolate between points to produce a continuous shape.
- [Lines](https://d3js.org/d3-shape/line) \- a spline or polyline, as in a line chart.
- [Links](https://d3js.org/d3-shape/link) \- a smooth cubic Bézier curve from a source to a target.
- [Pies](https://d3js.org/d3-shape/pie) \- compute angles for a pie or donut chart.
- [Stacks](https://d3js.org/d3-shape/stack) \- stack adjacent shapes, as in a stacked bar chart.
- [Symbols](https://d3js.org/d3-shape/symbol) \- a categorical shape encoding, as in a scatterplot.
- [Radial areas](https://d3js.org/d3-shape/radial-area) \- like [area](https://d3js.org/d3-shape/area), but in polar coordinates.
- [Radial lines](https://d3js.org/d3-shape/radial-line) \- like [line](https://d3js.org/d3-shape/line), but in polar coordinates.
- [Radial links](https://d3js.org/d3-shape/radial-link) \- like [link](https://d3js.org/d3-shape/link), but in polar coordinates.

## Random Number Generation
[Skip to content](https://d3js.org/d3-random#VPContent)

On this page

# d3-random [​](https://d3js.org/d3-random\#d3-random)

Generate random numbers from various distributions. For seeded random number generation, see [_random_.source](https://d3js.org/d3-random#random_source) and [randomLcg](https://d3js.org/d3-random#randomLcg).

## randomUniform( _min_, _max_) [​](https://d3js.org/d3-random\#randomUniform)

0123456

js

```
d3.randomUniform(6) // generate numbers ≥0 and <6
```

[Examples](https://observablehq.com/@d3/d3-random#uniform) · [Source](https://github.com/d3/d3-random/blob/main/src/uniform.js) · Returns a function for generating random numbers with a [uniform distribution](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)). The minimum allowed value of a returned number is _min_ (inclusive), and the maximum is _max_ (exclusive). If _min_ is not specified, it defaults to 0; if _max_ is not specified, it defaults to 1. For example:

## randomInt( _min_, _max_) [​](https://d3js.org/d3-random\#randomInt)

0102030405060708090100

js

```
d3.randomInt(100) // generate integers ≥0 and <100
```

[Examples](https://observablehq.com/@d3/d3-random#int) · [Source](https://github.com/d3/d3-random/blob/main/src/int.js) · Returns a function for generating random integers with a [uniform distribution](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)). The minimum allowed value of a returned number is ⌊ _min_⌋ (inclusive), and the maximum is ⌊ _max_ \- 1⌋ (inclusive). If _min_ is not specified, it defaults to 0. For example:

## randomNormal( _mu_, _sigma_) [​](https://d3js.org/d3-random\#randomNormal)

−4−3−2−101234

js

```
d3.randomNormal(0, 1) // mean of 0, and standard deviation of 1
```

[Examples](https://observablehq.com/@d3/d3-random#normal) · [Source](https://github.com/d3/d3-random/blob/main/src/normal.js) · Returns a function for generating random numbers with a [normal (Gaussian) distribution](https://en.wikipedia.org/wiki/Normal_distribution). The expected value of the generated numbers is _mu_, with the given standard deviation _sigma_. If _mu_ is not specified, it defaults to 0; if _sigma_ is not specified, it defaults to 1.

## randomLogNormal( _mu_, _sigma_) [​](https://d3js.org/d3-random\#randomLogNormal)

0246810121416

js

```
d3.randomLogNormal(0, 1)
```

[Examples](https://observablehq.com/@d3/d3-random#logNormal) · [Source](https://github.com/d3/d3-random/blob/main/src/logNormal.js) · Returns a function for generating random numbers with a [log-normal distribution](https://en.wikipedia.org/wiki/Log-normal_distribution). The expected value of the random variable’s natural logarithm is _mu_, with the given standard deviation _sigma_. If _mu_ is not specified, it defaults to 0; if _sigma_ is not specified, it defaults to 1.

## randomBates( _n_) [​](https://d3js.org/d3-random\#randomBates)

0.00.10.20.30.40.50.60.70.80.91.0

js

```
d3.randomBates(3) // generates numbers between 0 and 1
```

[Examples](https://observablehq.com/@d3/d3-random#bates) · [Source](https://github.com/d3/d3-random/blob/main/src/bates.js) · Returns a function for generating random numbers with a [Bates distribution](https://en.wikipedia.org/wiki/Bates_distribution) with _n_ independent variables. The case of fractional _n_ is handled as with d3.randomIrwinHall, and d3.randomBates(0) is equivalent to d3.randomUniform().

## randomIrwinHall( _n_) [​](https://d3js.org/d3-random\#randomIrwinHall)

0.00.51.01.52.02.53.0

js

```
d3.randomIrwinHall(3) // generates numbers between 0 and 3
```

[Examples](https://observablehq.com/@d3/d3-random#irwinHall) · [Source](https://github.com/d3/d3-random/blob/main/src/irwinHall.js) · Returns a function for generating random numbers with an [Irwin–Hall distribution](https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution) with _n_ independent variables. If the fractional part of _n_ is non-zero, this is treated as adding d3.randomUniform() times that fractional part to the integral part.

## randomExponential( _lambda_) [​](https://d3js.org/d3-random\#randomExponential)

020406080100120140160180200220240

js

```
d3.randomExponential(1 / 40)
```

[Examples](https://observablehq.com/@d3/d3-random#exponential) · [Source](https://github.com/d3/d3-random/blob/main/src/exponential.js) · Returns a function for generating random numbers with an [exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution) with the rate _lambda_; equivalent to time between events in a [Poisson process](https://en.wikipedia.org/wiki/Poisson_point_process) with a mean of 1 / _lambda_. For example, randomExponential(1 / 40) generates random times between events where, on average, one event occurs every 40 units of time.

## randomPareto( _alpha_) [​](https://d3js.org/d3-random\#randomPareto)

1.01.21.41.61.82.02.22.42.62.8

js

```
d3.randomPareto(6)
```

[Examples](https://observablehq.com/@d3/d3-random#pareto) · [Source](https://github.com/d3/d3-random/blob/main/src/pareto.js) · Returns a function for generating random numbers with a [Pareto distribution](https://en.wikipedia.org/wiki/Pareto_distribution) with the shape _alpha_. The value _alpha_ must be a positive value.

## randomBernoulli( _p_) [​](https://d3js.org/d3-random\#randomBernoulli)

01

js

```
d3.randomBernoulli(0.5)
```

[Examples](https://observablehq.com/@d3/d3-random#bernoulli) · [Source](https://github.com/d3/d3-random/blob/main/src/bernoulli.js) · Returns a function for generating either 1 or 0 according to a [Bernoulli distribution](https://en.wikipedia.org/wiki/Bernoulli_distribution) with 1 being returned with success probability _p_ and 0 with failure probability _q_ = 1 - _p_. The value _p_ is in the range \[0, 1\].

## randomGeometric( _p_) [​](https://d3js.org/d3-random\#randomGeometric)

0102030405060

js

```
d3.randomGeometric(0.1)
```

[Examples](https://observablehq.com/@d3/d3-random#geometric) · [Source](https://github.com/d3/d3-random/blob/main/src/geometric.js) · Returns a function for generating numbers with a [geometric distribution](https://en.wikipedia.org/wiki/Geometric_distribution) with success probability _p_. The value _p_ is in the range \[0, 1\].

## randomBinomial( _n_, _p_) [​](https://d3js.org/d3-random\#randomBinomial)

0510152025303540

js

```
d3.randomBinomial(40, 0.5)
```

[Examples](https://observablehq.com/@d3/d3-random#binomial) · [Source](https://github.com/d3/d3-random/blob/main/src/binomial.js) · Returns a function for generating random numbers with a [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution) with _n_ the number of trials and _p_ the probability of success in each trial. The value _n_ is greater or equal to 0, and the value _p_ is in the range \[0, 1\].

## randomGamma( _k_, _theta_) [​](https://d3js.org/d3-random\#randomGamma)

0123456789

js

```
d3.randomGamma(2, 1)
```

[Examples](https://observablehq.com/@parcly-taxel/the-gamma-and-beta-distributions) · [Source](https://github.com/d3/d3-random/blob/main/src/gamma.js) · Returns a function for generating random numbers with a [gamma distribution](https://en.wikipedia.org/wiki/Gamma_distribution) with _k_ the shape parameter and _theta_ the scale parameter. The value _k_ must be a positive value; if _theta_ is not specified, it defaults to 1.

## randomBeta( _alpha_, _beta_) [​](https://d3js.org/d3-random\#randomBeta)

0.00.10.20.30.40.50.60.70.80.91.0

js

```
d3.randomBeta(3, 1.5)
```

[Examples](https://observablehq.com/@parcly-taxel/the-gamma-and-beta-distributions) · [Source](https://github.com/d3/d3-random/blob/main/src/beta.js) · Returns a function for generating random numbers with a [beta distribution](https://en.wikipedia.org/wiki/Beta_distribution) with _alpha_ and _beta_ shape parameters, which must both be positive.

## randomWeibull( _k_, _a_, _b_) [​](https://d3js.org/d3-random\#randomWeibull)

0.40.50.60.70.80.91.01.11.21.3

js

```
d3.randomWeibull(10)
```

[Examples](https://observablehq.com/@parcly-taxel/frechet-gumbel-weibull) · [Source](https://github.com/d3/d3-random/blob/main/src/weibull.js) · Returns a function for generating random numbers with one of the [generalized extreme value distributions](https://en.wikipedia.org/wiki/Generalized_extreme_value_distribution), depending on _k_:

- If _k_ is positive, the [Weibull distribution](https://en.wikipedia.org/wiki/Weibull_distribution) with shape parameter _k_
- If _k_ is zero, the [Gumbel distribution](https://en.wikipedia.org/wiki/Gumbel_distribution)
- If _k_ is negative, the [Fréchet distribution](https://en.wikipedia.org/wiki/Fr%C3%A9chet_distribution) with shape parameter − _k_

In all three cases, _a_ is the location parameter and _b_ is the scale parameter. If _a_ is not specified, it defaults to 0; if _b_ is not specified, it defaults to 1.

## randomCauchy( _a_, _b_) [​](https://d3js.org/d3-random\#randomCauchy)

−5−4−3−2−1012345

js

```
d3.randomCauchy(0, 1) // above, clipped to [-5, 5] because “fat tails”
```

[Examples](https://observablehq.com/@parcly-taxel/cauchy-and-logistic-distributions) · [Source](https://github.com/d3/d3-random/blob/main/src/cauchy.js) · Returns a function for generating random numbers with a [Cauchy distribution](https://en.wikipedia.org/wiki/Cauchy_distribution). _a_ and _b_ have the same meanings and default values as in d3.randomWeibull.

## randomLogistic( _a_, _b_) [​](https://d3js.org/d3-random\#randomLogistic)

−10−8−6−4−20246810

js

```
d3.randomLogistic(0, 1)
```

[Examples](https://observablehq.com/@parcly-taxel/cauchy-and-logistic-distributions) · [Source](https://github.com/d3/d3-random/blob/main/src/logistic.js) · Returns a function for generating random numbers with a [logistic distribution](https://en.wikipedia.org/wiki/Logistic_distribution). _a_ and _b_ have the same meanings and default values as in d3.randomWeibull.

## randomPoisson( _lambda_) [​](https://d3js.org/d3-random\#randomPoisson)

340360380400420440460

js

```
d3.randomPoisson(400)
```

[Examples](https://observablehq.com/@parcly-taxel/the-poisson-distribution) · [Source](https://github.com/d3/d3-random/blob/main/src/poisson.js) · Returns a function for generating random numbers with a [Poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution) with mean _lambda_.

## _random_.source( _source_) [​](https://d3js.org/d3-random\#random_source)

js

```
const seed = 0.44871573888282423; // any number in [0, 1)\
const random = d3.randomNormal.source(d3.randomLcg(seed))(0, 1);\
random(); // -0.6253955998897069\
```\
\
[Examples](https://observablehq.com/@d3/random-source) · Returns the same type of function for generating random numbers but where the given random number generator _source_ is used as the source of randomness instead of Math.random. The given random number generator must implement the same interface as Math.random and only return values in the range \[0, 1). This is useful when a seeded random number generator is preferable to Math.random.\
\
## randomLcg( _seed_) [​](https://d3js.org/d3-random\#randomLcg)\
\
0.00.10.20.30.40.50.60.70.80.91.0\
\
js\
\
```\
d3.randomLcg(42)\
```\
\
[Examples](https://observablehq.com/@d3/d3-randomlcg) · [Source](https://github.com/d3/d3-random/blob/main/src/lcg.js) · Returns a [linear congruential generator](https://en.wikipedia.org/wiki/Linear_congruential_generator); this function can be called repeatedly to obtain pseudorandom values well-distributed on the interval \[0,1) and with a long period (up to 1 billion numbers), similar to Math.random. A _seed_ can be specified as a real number in the interval \[0,1) or as any integer. In the latter case, only the lower 32 bits are considered. Two generators instanced with the same seed generate the same sequence, allowing to create reproducible pseudo-random experiments. If the _seed_ is not specified, one is chosen using Math.random.

## Transform Interpolation Methods
[Skip to content](https://d3js.org/d3-interpolate/transform#VPContent)

On this page

# Transform interpolation [​](https://d3js.org/d3-interpolate/transform\#transform-interpolation)

Interpolators for CSS and SVG transforms. The interpolation method is standardized by CSS: see [matrix decomposition for animation](http://www.w3.org/TR/css3-2d-transforms/#matrix-decomposition).

## interpolateTransformCss( _a_, _b_) [​](https://d3js.org/d3-interpolate/transform\#interpolateTransformCss)

js

```
d3.interpolateTransformCss("translateY(12px) scale(2)", "translateX(30px) rotate(5deg)")(0.5) // "translate(15px,6px) rotate(2.5deg) scale(1.5,1.5)"
```

[Examples](https://observablehq.com/@d3/d3-interpolatetransformcss) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/transform/index.js) · Returns an interpolator between the two 2D CSS transforms represented by _a_ and _b_. Each transform is decomposed to a standard representation of translate, rotate, _x_-skew and scale; these component transformations are then interpolated.

## interpolateTransformSvg( _a_, _b_) [​](https://d3js.org/d3-interpolate/transform\#interpolateTransformSvg)

js

```
d3.interpolateTransformSvg("skewX(-60)", "skewX(60) translate(280,0)") // "translate(140,0) skewX(0)"
```

[Examples](https://observablehq.com/@d3/d3-interpolatetransformcss) · [Source](https://github.com/d3/d3-interpolate/blob/main/src/transform/index.js) · Returns an interpolator between the two 2D SVG transforms represented by _a_ and _b_. Each transform is decomposed to a standard representation of translate, rotate, _x_-skew and scale; these component transformations are then interpolated.

## D3.js Circle Packing
[Skip to content](https://d3js.org/d3-hierarchy/pack#VPContent)

On this page

# Pack [​](https://d3js.org/d3-hierarchy/pack\#Pack)

[![Circle-Packing](https://raw.githubusercontent.com/d3/d3-hierarchy/main/img/pack.png)](https://observablehq.com/@d3/circle-packing)

[Examples](https://observablehq.com/@d3/circle-packing) · Enclosure diagrams use containment (nesting) to represent a hierarchy. The size of the leaf circles encodes a quantitative dimension of the data. The enclosing circles show the approximate cumulative size of each subtree, but due to wasted space there is some distortion; only the leaf nodes can be compared accurately. Although [circle packing](http://en.wikipedia.org/wiki/Circle_packing) does not use space as efficiently as a [treemap](https://d3js.org/d3-hierarchy/treemap), the “wasted” space more prominently reveals the hierarchical structure.

## pack() [​](https://d3js.org/d3-hierarchy/pack\#pack)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/pack/index.js) · Creates a new pack layout with the default settings.

### _pack_( _root_) [​](https://d3js.org/d3-hierarchy/pack\#_pack)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/pack/index.js) · Lays out the specified _root_ [hierarchy](https://d3js.org/d3-hierarchy/hierarchy), assigning the following properties on _root_ and its descendants:

- _node_.x - the _x_-coordinate of the circle’s center
- _node_.y - the y coordinate of the circle’s center
- _node_.r - the radius of the circle

You must call [_root_.sum](https://d3js.org/d3-hierarchy/hierarchy#node_sum) before passing the hierarchy to the pack layout. You probably also want to call [_root_.sort](https://d3js.org/d3-hierarchy/hierarchy#node_sort) to order the hierarchy before computing the layout.

## _pack_.radius( _radius_) [​](https://d3js.org/d3-hierarchy/pack\#pack_radius)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/pack/index.js) · If _radius_ is specified, sets the pack layout’s radius accessor to the specified function and returns this pack layout. If _radius_ is not specified, returns the current radius accessor, which defaults to null. If the radius accessor is null, the radius of each leaf circle is derived from the leaf _node_.value (computed by [_node_.sum](https://d3js.org/d3-hierarchy/hierarchy#node_sum)); the radii are then scaled proportionally to fit the [layout size](https://d3js.org/d3-hierarchy/pack#pack_size). If the radius accessor is not null, the radius of each leaf circle is specified exactly by the function.

## _pack_.size( _size_) [​](https://d3js.org/d3-hierarchy/pack\#pack_size)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/pack/index.js) · If _size_ is specified, sets this pack layout’s size to the specified two-element array of numbers \[ _width_, _height_\] and returns this pack layout. If _size_ is not specified, returns the current size, which defaults to \[1, 1\].

## _pack_.padding( _padding_) [​](https://d3js.org/d3-hierarchy/pack\#pack_padding)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/pack/index.js) · If _padding_ is specified, sets this pack layout’s padding accessor to the specified number or function and returns this pack layout. If _padding_ is not specified, returns the current padding accessor, which defaults to the constant zero. When siblings are packed, tangent siblings will be separated by approximately the specified padding; the enclosing parent circle will also be separated from its children by approximately the specified padding. If an [explicit radius](https://d3js.org/d3-hierarchy/pack#pack_radius) is not specified, the padding is approximate because a two-pass algorithm is needed to fit within the [layout size](https://d3js.org/d3-hierarchy/pack#pack_size): the circles are first packed without padding; a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding.

## packSiblings( _circles_) [​](https://d3js.org/d3-hierarchy/pack\#packSiblings)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/pack/siblings.js) · Packs the specified array of _circles_, each of which must have a _circle_.r property specifying the circle’s radius. Assigns the following properties to each circle:

- _circle_.x - the _x_-coordinate of the circle’s center
- _circle_.y - the y coordinate of the circle’s center

The circles are positioned according to the front-chain packing algorithm by [Wang _et al._](https://dl.acm.org/citation.cfm?id=1124851)

## packEnclose( _circles_) [​](https://d3js.org/d3-hierarchy/pack\#packEnclose)

[Examples](https://observablehq.com/@d3/d3-packenclose) · [Source](https://github.com/d3/d3-hierarchy/blob/main/src/pack/enclose.js) · Computes the [smallest circle](https://en.wikipedia.org/wiki/Smallest-circle_problem) that encloses the specified array of _circles_, each of which must have a _circle_.r property specifying the circle’s radius, and _circle_.x and _circle_.y properties specifying the circle’s center. The enclosing circle is computed using the [Matoušek-Sharir-Welzl algorithm](http://www.inf.ethz.ch/personal/emo/PublFiles/SubexLinProg_ALG16_96.pdf). (See also [Apollonius’ Problem](https://observablehq.com/@d3/apollonius-problem).)

## D3.js Summary Statistics
[Skip to content](https://d3js.org/d3-array/summarize#VPContent)

On this page

# Summarizing data [​](https://d3js.org/d3-array/summarize\#summarizing-data)

Compute summary statistics.

## count( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#count)

js

```
d3.count(penguins, (d) => d.body_mass_g) // 342
```

[Examples](https://observablehq.com/@d3/d3-count) · [Source](https://github.com/d3/d3-array/blob/main/src/count.js) · Returns the number of valid number values ( _i.e._, not null, NaN, or undefined) in the specified _iterable_; accepts an accessor.

## min( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#min)

[Examples](https://observablehq.com/@d3/d3-extent) · [Source](https://github.com/d3/d3-array/blob/main/src/min.js) · Returns the minimum value in the given _iterable_ using natural order.

js

```
d3.min([3, 2, 1, 1, 6, 2, 4]) // 1
```

Unlike [Math.min](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/min), d3.min does not coerce the inputs to numbers; for example, the minimum of the strings `["20", "3"]` is `"20"`, while the minimum of the numbers `[20, 3]` is `3`.

js

```
d3.min(["bob", "alice", "carol"]) // "alice"
```

js

```
d3.min([new Date("2018-01-01"), new Date("2011-03-09")]) // 2011-03-09
```

Also unlike Math.min, this method ignores undefined, null and NaN values, which is useful for ignoring missing data.

js

```
d3.min([3, 2, 1, NaN, 4]) // 1
```

An optional _accessor_ function may be specified, which is similar to calling [Array.from](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) before computing the minimum value. The accessor function is repeatedly passed an element from the given iterable (often _d_) and the zero-based index ( _i_).

js

```
d3.min(alphabet, (d) => d.frequency) // 0.00074
```

Because undefined values are ignored, you can use the accessor function to ignore values. For example, to get the frequency of the least-common letter than is not Z:

js

```
d3.min(alphabet, (d) => d.letter === "Z" ? NaN : d.frequency) // 0.00095
```

If the iterable contains no comparable values, returns undefined.

js

```
d3.min([]) // undefined
```

js

```
d3.min(alphabet, (d) => d.doesnotexist) // undefined
```

See also [extent](https://d3js.org/d3-array/summarize#extent) and [least](https://d3js.org/d3-array/summarize#least).

## minIndex( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#minIndex)

[Source](https://github.com/d3/d3-array/blob/main/src/minIndex.js) · Like [min](https://d3js.org/d3-array/summarize#min), but returns the index of the minimum value rather than the value itself.

js

```
d3.minIndex([3, 2, 1, 1, 6, 2, 4]) // 2
```

This method can find the least element according to the given accessor, similar to [least](https://d3js.org/d3-array/summarize#least):

js

```
d3.minIndex(alphabet, (d) => d.frequency) // 25
```

js

```
alphabet[d3.minIndex(alphabet, (d) => d.frequency)] // {letter: "Z", frequency: 0.00074}
```

See also [leastIndex](https://d3js.org/d3-array/summarize#leastIndex).

## max( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#max)

[Examples](https://observablehq.com/@d3/d3-extent) · [Source](https://github.com/d3/d3-array/blob/main/src/max.js) · Returns the maximum value in the given _iterable_ using natural order.

js

```
d3.max([3, 2, 1, 1, 6, 2, 4]) // 6
```

Unlike [Math.max](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/max), d3.max does not coerce the inputs to numbers; for example, the maximum of the strings `["20", "3"]` is `"3"`, while the maximum of the numbers `[20, 3]` is `20`.

js

```
d3.max(["bob", "alice", "carol"]) // "carol"
```

js

```
d3.max([new Date("2018-01-01"), new Date("2011-03-09")]) // 2018-01-01
```

Also unlike Math.max, this method ignores undefined, null and NaN values, which is useful for ignoring missing data.

js

```
d3.max([3, 2, 1, NaN, 4]) // 4
```

An optional _accessor_ function may be specified, which is similar to calling [Array.from](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) before computing the maximum value. The accessor function is repeatedly passed an element from the given iterable (often _d_) and the zero-based index ( _i_).

js

```
d3.max(alphabet, (d) => d.frequency) // 0.12702
```

Because undefined values are ignored, you can use the accessor function to ignore values. For example, to get the frequency of the most-common letter than is not E:

js

```
d3.max(alphabet, (d) => d.letter === "E" ? NaN : d.frequency) // 0.09056
```

If the iterable contains no comparable values, returns undefined.

js

```
d3.max([]) // undefined
```

js

```
d3.max(alphabet, (d) => d.doesnotexist) // undefined
```

See also [extent](https://d3js.org/d3-array/summarize#extent) and [greatest](https://d3js.org/d3-array/summarize#greatest).

## maxIndex( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#maxIndex)

[Source](https://github.com/d3/d3-array/blob/main/src/maxIndex.js) · Like [max](https://d3js.org/d3-array/summarize#max), but returns the index of the maximum value rather than the value itself.

js

```
d3.maxIndex([3, 2, 1, 1, 6, 2, 4]) // 2
```

This method can find the greatest element according to the given accessor, similar to [greatest](https://d3js.org/d3-array/summarize#greatest):

js

```
d3.maxIndex(alphabet, (d) => d.frequency) // 0
```

js

```
alphabet[d3.maxIndex(alphabet, (d) => d.frequency)] // {letter: "E", frequency: 0.12702}
```

See also [greatestIndex](https://d3js.org/d3-array/summarize#greatestIndex).

## least( _iterable_, _comparator_) [​](https://d3js.org/d3-array/summarize\#least)

[Examples](https://observablehq.com/@d3/d3-least) · [Source](https://github.com/d3/d3-array/blob/main/src/least.js) · Returns the least element of the specified _iterable_ according to the specified _comparator_.

js

```
d3.least(alphabet, (a, b) => a.frequency - b.frequency) // {letter: "Z", frequency: 0.00074}
```

js

```
d3.least(alphabet, (a, b) => b.frequency - a.frequency) // {letter: "E", frequency: 0.12702}
```

If the _comparator_ takes a single argument, is interpreted as an accessor and the returned elements are compared using natural order.

js

```
d3.least(alphabet, (d) => d.frequency) // {letter: "Z", frequency: 0.00074}
```

js

```
d3.least(alphabet, (d) => -d.frequency) // {letter: "E", frequency: 0.12702}
```

If _comparator_ is not specified, it defaults to [ascending](https://d3js.org/d3-array/sort#ascending).

js

```
d3.least(alphabet.map((d) => d.frequency)) // 0.00074
```

If the given _iterable_ contains no comparable elements ( _i.e._, the comparator returns NaN when comparing each element to itself), returns undefined.

js

```
d3.least([]) // undefined
```

This function is similar to [min](https://d3js.org/d3-array/summarize#min), except it allows the use of a comparator rather than an accessor.

## leastIndex( _iterable_, _comparator_) [​](https://d3js.org/d3-array/summarize\#leastIndex)

[Source](https://github.com/d3/d3-array/blob/main/src/leastIndex.js) · Returns the index of the least element of the specified _iterable_ according to the specified _comparator_ or _accessor_. If the given _iterable_ contains no comparable elements ( _i.e._, the comparator returns NaN when comparing each element to itself), returns -1. If _comparator_ is not specified, it defaults to [ascending](https://d3js.org/d3-array/sort#ascending). For example:

js

```
const array = [{foo: 42}, {foo: 91}];
d3.leastIndex(array, (a, b) => a.foo - b.foo); // 0
d3.leastIndex(array, (a, b) => b.foo - a.foo); // 1
d3.leastIndex(array, (d) => d.foo); // 0
```

This function is similar to [minIndex](https://d3js.org/d3-array/summarize#minIndex), except it allows the use of a comparator rather than an accessor.

## greatest( _iterable_, _comparator_) [​](https://d3js.org/d3-array/summarize\#greatest)

[Examples](https://observablehq.com/@d3/d3-least) · [Source](https://github.com/d3/d3-array/blob/main/src/greatest.js) · Returns the greatest element of the specified _iterable_ according to the specified _comparator_ or _accessor_. If the given _iterable_ contains no comparable elements ( _i.e._, the comparator returns NaN when comparing each element to itself), returns undefined. If _comparator_ is not specified, it defaults to [ascending](https://d3js.org/d3-array/sort#ascending). For example:

js

```
const array = [{foo: 42}, {foo: 91}];
d3.greatest(array, (a, b) => a.foo - b.foo); // {foo: 91}
d3.greatest(array, (a, b) => b.foo - a.foo); // {foo: 42}
d3.greatest(array, (d) => d.foo); // {foo: 91}
```

This function is similar to [max](https://d3js.org/d3-array/summarize#max), except it allows the use of a comparator rather than an accessor.

## greatestIndex( _iterable_, _comparator_) [​](https://d3js.org/d3-array/summarize\#greatestIndex)

[Source](https://github.com/d3/d3-array/blob/main/src/greatestIndex.js) · Returns the index of the greatest element of the specified _iterable_ according to the specified _comparator_ or _accessor_. If the given _iterable_ contains no comparable elements ( _i.e._, the comparator returns NaN when comparing each element to itself), returns -1. If _comparator_ is not specified, it defaults to [ascending](https://d3js.org/d3-array/sort#ascending). For example:

js

```
const array = [{foo: 42}, {foo: 91}];
d3.greatestIndex(array, (a, b) => a.foo - b.foo); // 1
d3.greatestIndex(array, (a, b) => b.foo - a.foo); // 0
d3.greatestIndex(array, (d) => d.foo); // 1
```

This function is similar to [maxIndex](https://d3js.org/d3-array/summarize#maxIndex), except it allows the use of a comparator rather than an accessor.

## extent( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#extent)

[Examples](https://observablehq.com/@d3/d3-extent) · [Source](https://github.com/d3/d3-array/blob/main/src/extent.js) · Returns the [minimum](https://d3js.org/d3-array/summarize#min) and [maximum](https://d3js.org/d3-array/summarize#max) value in the given _iterable_ using natural order.

js

```
d3.extent([3, 2, 1, 1, 6, 2, 4]) // [1, 6]
```

An optional _accessor_ function may be specified, which is equivalent to calling Array.from before computing the extent.

js

```
d3.extent(alphabet, (d) => d.frequency) // [0.00074, 0.12702]
```

If the iterable contains no comparable values, returns \[undefined, undefined\].

js

```
d3.extent(alphabet, (d) => d.doesnotexist) // [undefined, undefined]
```

## mode( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#mode)

[Examples](https://observablehq.com/@d3/d3-mode) · [Source](https://github.com/d3/d3-array/blob/main/src/mode.js) · Returns the mode of the given _iterable_, _i.e._ the value which appears the most often. Ignores undefined, null and NaN values.

js

```
d3.mode([1, 2, 2, 2, 3, 3]) // 2
```

An optional _accessor_ function may be specified, which is equivalent to calling Array.from before computing the mode.

js

```
d3.mode(penguins, (d) => d.island) // "Biscoe"
```

In case of equality, returns the first of the relevant values. If the iterable contains no comparable values, returns undefined.

## sum( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#sum)

[Examples](https://observablehq.com/@d3/d3-sum) · [Source](https://github.com/d3/d3-array/blob/main/src/sum.js) · Returns the sum of the given _iterable_ of numbers. Ignores undefined, null and NaN values.

js

```
d3.sum([1, 2, 2, 2, NaN, 3, null]) // 10
```

An optional _accessor_ function may be specified, which is equivalent to calling Array.from before computing the sum.

js

```
d3.sum(penguins, (d) => d.body_mass_g) // 1437000
```

If the iterable contains no numbers, returns 0. See also [fsum](https://d3js.org/d3-array/add#fsum).

## mean( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#mean)

[Examples](https://observablehq.com/@d3/d3-mean-d3-median-and-friends) · [Source](https://github.com/d3/d3-array/blob/main/src/mean.js) · Returns the mean of the given _iterable_ of numbers. Ignores undefined, null and NaN values.

js

```
d3.mean([1, 2, 2, 2, NaN, 3, null]) // 2
```

An optional _accessor_ function may be specified, which is equivalent to calling Array.from before computing the mean.

js

```
d3.mean(penguins, (d) => d.body_mass_g) // 4201.754385964912
```

If the iterable contains no numbers, returns undefined.

## median( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#median)

[Examples](https://observablehq.com/@d3/d3-mean-d3-median-and-friends) · [Source](https://github.com/d3/d3-array/blob/main/src/median.js) · Returns the median of the given _iterable_ of numbers using the [R-7 method](https://en.wikipedia.org/wiki/Quantile#Estimating_quantiles_from_a_sample). Ignores undefined, null and NaN values.

js

```
d3.median([1, 2, 2, 2, NaN, 3, null]) // 2
```

An optional _accessor_ function may be specified, which is equivalent to calling Array.from before computing the median.

js

```
d3.median(penguins, (d) => d.body_mass_g) // 4050
```

If the iterable contains no numbers, returns undefined.

## medianIndex(array, accessor) [​](https://d3js.org/d3-array/summarize\#medianIndex)

[Source](https://github.com/d3/d3-array/blob/main/src/median.js) · Like [median](https://d3js.org/d3-array/summarize#median), but returns the index of the element to the left of the median.

js

```
d3.medianIndex([1, 2, 2, 2, NaN, 3, null]) // 2
```

## cumsum( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#cumsum)

[Examples](https://observablehq.com/@d3/d3-cumsum) · [Source](https://github.com/d3/d3-array/blob/main/src/cumsum.js) · Returns the cumulative sum of the given _iterable_ of numbers, as a Float64Array of the same length.

js

```
d3.cumsum([1, 1, 2, 3, 5]) // [1, 2, 4, 7, 12]
```

An optional _accessor_ function may be specified, which is equivalent to calling Array.from before computing the cumulative sum.

js

```
d3.cumsum(penguins, (d) => d.body_mass_g) // [3750, 7550, 10800, 10800, …]
```

This method ignores undefined and NaN values; this is useful for ignoring missing data. If the iterable contains no numbers, returns zeros. See also [fcumsum](https://d3js.org/d3-array/add#fcumsum).

## quantile( _iterable_, _p_, _accessor_) [​](https://d3js.org/d3-array/summarize\#quantile)

[Examples](https://observablehq.com/@d3/d3-mean-d3-median-and-friends) · [Source](https://github.com/d3/d3-array/blob/main/src/quantile.js) · Returns the _p_-quantile of the given _iterable_ of numbers, where _p_ is a number in the range \[0, 1\]. For example, the median can be computed using _p_ = 0.5, the first quartile at _p_ = 0.25, and the third quartile at _p_ = 0.75. This particular implementation uses the [R-7 method](http://en.wikipedia.org/wiki/Quantile#Quantiles_of_a_population), which is the default for the R programming language and Excel.

js

```
const numbers = [0, 10, 30];
d3.quantile(numbers, 0); // 0
d3.quantile(numbers, 0.5); // 10
d3.quantile(numbers, 1); // 30
d3.quantile(numbers, 0.25); // 5
d3.quantile(numbers, 0.75); // 20
d3.quantile(numbers, 0.1); // 2
```

An optional _accessor_ function may be specified, which is equivalent to calling [_array_.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) before computing the quantile.

## quantileIndex( _array_, _p_, _accessor_) [​](https://d3js.org/d3-array/summarize\#quantileIndex)

[Source](https://github.com/d3/d3-array/blob/main/src/quantile.js) · Similar to _quantile_, but returns the index to the left of _p_.

## quantileSorted( _array_, _p_, _accessor_) [​](https://d3js.org/d3-array/summarize\#quantileSorted)

[Examples](https://observablehq.com/@d3/d3-mean-d3-median-and-friends) · [Source](https://github.com/d3/d3-array/blob/main/src/quantile.js) · Similar to _quantile_, but expects the input to be a **sorted** _array_ of values. In contrast with _quantile_, the accessor is only called on the elements needed to compute the quantile.

## rank( _iterable_, _comparator_) [​](https://d3js.org/d3-array/summarize\#rank)

[Examples](https://observablehq.com/@d3/rank) · [Source](https://github.com/d3/d3-array/blob/main/src/rank.js) · Returns an array with the rank of each value in the _iterable_, _i.e._ the zero-based index of the value when the iterable is sorted. Nullish values are sorted to the end and ranked NaN. An optional _comparator_ or _accessor_ function may be specified; the latter is equivalent to calling [_array_.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) before computing the ranks. If _comparator_ is not specified, it defaults to [ascending](https://d3js.org/d3-array/sort#ascending). Ties (equivalent values) all get the same rank, defined as the first time the value is found.

js

```
d3.rank([{x: 1}, {}, {x: 2}, {x: 0}], d => d.x); // [1, NaN, 2, 0]
d3.rank(["b", "c", "b", "a"]); // [1, 3, 1, 0]
d3.rank([1, 2, 3], d3.descending); // [2, 1, 0]
```

## variance( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#variance)

[Examples](https://observablehq.com/@d3/d3-mean-d3-median-and-friends) · [Source](https://github.com/d3/d3-array/blob/main/src/variance.js) · Returns an [unbiased estimator of the population variance](http://mathworld.wolfram.com/SampleVariance.html) of the given _iterable_ of numbers using [Welford’s algorithm](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm). If the iterable has fewer than two numbers, returns undefined. An optional _accessor_ function may be specified, which is equivalent to calling Array.from before computing the variance. This method ignores undefined and NaN values; this is useful for ignoring missing data.

## deviation( _iterable_, _accessor_) [​](https://d3js.org/d3-array/summarize\#deviation)

[Examples](https://observablehq.com/@d3/d3-mean-d3-median-and-friends) · [Source](https://github.com/d3/d3-array/blob/main/src/deviation.js) · Returns the standard deviation, defined as the square root of the [bias-corrected variance](https://d3js.org/d3-array/summarize#variance), of the given _iterable_ of numbers. If the iterable has fewer than two numbers, returns undefined. An optional _accessor_ function may be specified, which is equivalent to calling Array.from before computing the standard deviation. This method ignores undefined and NaN values; this is useful for ignoring missing data.

## every( _iterable_, _test_) [​](https://d3js.org/d3-array/summarize\#every)

[Source](https://github.com/d3/d3-array/blob/main/src/every.js) · Returns true if the given _test_ function returns true for every value in the given _iterable_. This method returns as soon as _test_ returns a non-truthy value or all values are iterated over. Equivalent to [_array_.every](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every):

js

```
d3.every(new Set([1, 3, 5, 7]), x => x & 1) // true
```

## some( _iterable_, _test_) [​](https://d3js.org/d3-array/summarize\#some)

[Source](https://github.com/d3/d3-array/blob/main/src/some.js) · Returns true if the given _test_ function returns true for any value in the given _iterable_. This method returns as soon as _test_ returns a truthy value or all values are iterated over. Equivalent to [_array_.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some):

js

```
d3.some(new Set([0, 2, 3, 4]), x => x & 1) // true
```

## Symlog Scales
[Skip to content](https://d3js.org/d3-scale/symlog#VPContent)

On this page

# Symlog scales [​](https://d3js.org/d3-scale/symlog\#symlog-scales)

See [A bi-symmetric log transformation for wide-range data](https://www.researchgate.net/profile/John_Webber4/publication/233967063_A_bi-symmetric_log_transformation_for_wide-range_data/links/0fcfd50d791c85082e000000.pdf) by Webber for details. Unlike a [log scale](https://d3js.org/d3-scale/log), a symlog scale domain can include zero.

## scaleSymlog( _domain_, _range_) [​](https://d3js.org/d3-scale/symlog\#scaleSymlog)

[Examples](https://observablehq.com/@d3/continuous-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/symlog.js) · Constructs a new continuous scale with the specified [domain](https://d3js.org/d3-scale/linear#linear_domain) and [range](https://d3js.org/d3-scale/linear#linear_range), the [constant](https://d3js.org/d3-scale/symlog#symlog_constant) 1, the [default](https://d3js.org/d3-interpolate/value#interpolate) [interpolator](https://d3js.org/d3-scale/linear#linear_interpolate) and [clamping](https://d3js.org/d3-scale/linear#linear_clamp) disabled.

js

```
const x = d3.scaleSymlog([0, 100], [0, 960]);
```

If a single argument is specified, it is interpreted as the _range_. If either _domain_ or _range_ are not specified, each defaults to \[0, 1\].

js

```
const color = d3.scaleSymlog(["red", "blue"]) // default domain of [0, 1]
```

## _symlog_.constant( _constant_) [​](https://d3js.org/d3-scale/symlog\#symlog_constant)

[Examples](https://observablehq.com/@d3/continuous-scales) · [Source](https://github.com/d3/d3-scale/blob/main/src/symlog.js) · If _constant_ is specified, sets the symlog constant to the specified number and returns this scale. The constant defaults to 1.

js

```
const x = d3.scaleSymlog([0, 100], [0, 960]).constant(2);
```

If _constant_ is not specified, returns the current value of the symlog constant.

js

```
x.constant() // 2
```

## D3.js Control Flow
[Skip to content](https://d3js.org/d3-selection/control-flow#VPContent)

On this page

# Control flow [​](https://d3js.org/d3-selection/control-flow\#control-flow)

For advanced usage, selections provide methods for custom control flow.

## _selection_.each( _function_) [​](https://d3js.org/d3-selection/control-flow\#selection_each)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/each.js) · Invokes the specified _function_ for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). This method can be used to invoke arbitrary code for each selected element, and is useful for creating a context to access parent and child data simultaneously, such as:

js

```
parent.each(function(p, j) {
  d3.select(this)
    .selectAll(".child")
      .text(d => `child ${d.name} of ${p.name}`);
});
```

See [sized donut multiples](https://observablehq.com/@d3/sized-donut-multiples) for an example.

## _selection_.call( _function_, ... _arguments_) [​](https://d3js.org/d3-selection/control-flow\#selection_call)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/call.js) · Invokes the specified _function_ exactly once, passing in this selection along with any optional _arguments_. Returns this selection. This is equivalent to invoking the function by hand but facilitates method chaining. For example, to set several styles in a reusable function:

js

```
function name(selection, first, last) {
  selection
      .attr("first-name", first)
      .attr("last-name", last);
}
```

Now say:

js

```
d3.selectAll("div").call(name, "John", "Snow");
```

This is roughly equivalent to:

js

```
name(d3.selectAll("div"), "John", "Snow");
```

The only difference is that _selection_.call always returns the _selection_ and not the return value of the called _function_, `name`.

## _selection_.empty() [​](https://d3js.org/d3-selection/control-flow\#selection_empty)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/empty.js) · Returns true if this selection contains no (non-null) elements.

js

```
d3.selectAll("p").empty() // false, here
```

## _selection_.nodes() [​](https://d3js.org/d3-selection/control-flow\#selection_nodes)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/nodes.js) · Returns an array of all (non-null) elements in this selection.

js

```
d3.selectAll("p").nodes() // [p, p, p, …]
```

Equivalent to:

js

```
Array.from(selection)
```

## _selection_\[Symbol.iterator\]() [​](https://d3js.org/d3-selection/control-flow\#selection_iterator)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/iterator.js) · Returns an iterator over the selected (non-null) elements. For example, to iterate over the selected elements:

js

```
for (const element of selection) {
  console.log(element);
}
```

To flatten the selection to an array:

js

```
const elements = [...selection];
```

## _selection_.node() [​](https://d3js.org/d3-selection/control-flow\#selection_node)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/node.js) · Returns the first (non-null) element in this selection. If the selection is empty, returns null.

## _selection_.size() [​](https://d3js.org/d3-selection/control-flow\#selection_size)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/size.js) · Returns the total number of (non-null) elements in this selection.

## D3 Transition Control Flow
[Skip to content](https://d3js.org/d3-transition/control-flow#VPContent)

On this page

# Control flow [​](https://d3js.org/d3-transition/control-flow\#control-flow)

For advanced usage, transitions provide methods for custom control flow.

## The life of a transition [​](https://d3js.org/d3-transition/control-flow\#the-life-of-a-transition)

Immediately after creating a transition, such as by [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition) or [_transition_.transition](https://d3js.org/d3-transition/selecting#transition_transition), you may configure the transition using methods such as [_transition_.delay](https://d3js.org/d3-transition/timing#transition_delay), [_transition_.duration](https://d3js.org/d3-transition/timing#transition_duration), [_transition_.attr](https://d3js.org/d3-transition/modifying#transition_attr) and [_transition_.style](https://d3js.org/d3-transition/modifying#transition_style). Methods that specify target values (such as _transition_.attr) are evaluated synchronously; however, methods that require the starting value for interpolation, such as [_transition_.attrTween](https://d3js.org/d3-transition/modifying#transition_attrTween) and [_transition_.styleTween](https://d3js.org/d3-transition/modifying#transition_styleTween), must be deferred until the transition starts.

Shortly after creation, either at the end of the current frame or during the next frame, the transition is scheduled. At this point, the delay and `start` event listeners may no longer be changed; attempting to do so throws an error with the message “too late: already scheduled” (or if the transition has ended, “transition not found”).

When the transition subsequently starts, it interrupts the active transition of the same name on the same element, if any, dispatching an `interrupt` event to registered listeners. (Note that interrupts happen on start, not creation, and thus even a zero-delay transition will not immediately interrupt the active transition: the old transition is given a final frame. Use [_selection_.interrupt](https://d3js.org/d3-transition/control-flow#selection_interrupt) to interrupt immediately.) The starting transition also cancels any pending transitions of the same name on the same element that were created before the starting transition. The transition then dispatches a `start` event to registered listeners. This is the last moment at which the transition may be modified: the transition’s timing, tweens, and listeners may not be changed when it is running; attempting to do so throws an error with the message “too late: already running” (or if the transition has ended, “transition not found”). The transition initializes its tweens immediately after starting.

During the frame the transition starts, but _after_ all transitions starting this frame have been started, the transition invokes its tweens for the first time. Batching tween initialization, which typically involves reading from the DOM, improves performance by avoiding interleaved DOM reads and writes.

For each frame that a transition is active, it invokes its tweens with an [eased](https://d3js.org/d3-transition/timing#transition_ease) _t_-value ranging from 0 to 1. Within each frame, the transition invokes its tweens in the order they were registered.

When a transition ends, it invokes its tweens a final time with a (non-eased) _t_-value of 1. It then dispatches an `end` event to registered listeners. This is the last moment at which the transition may be inspected: after ending, the transition is deleted from the element, and its configuration is destroyed. (A transition’s configuration is also destroyed on interrupt or cancel.) Attempting to inspect a transition after it is destroyed throws an error with the message “transition not found”.

## _selection_.interrupt( _name_) [​](https://d3js.org/d3-transition/control-flow\#selection_interrupt)

[Source](https://github.com/d3/d3-transition/blob/main/src/selection/interrupt.js) · Interrupts the active transition of the specified _name_ on the selected elements, and cancels any pending transitions with the specified _name_, if any. If a name is not specified, null is used.

Interrupting a transition on an element has no effect on any transitions on any descendant elements. For example, an [axis transition](https://d3js.org/d3-axis) consists of multiple independent, synchronized transitions on the descendants of the axis [G element](https://www.w3.org/TR/SVG/struct.html#Groups) (the tick lines, the tick labels, the domain path, _etc._). To interrupt the axis transition, you must therefore interrupt the descendants:

js

```
selection.selectAll("*").interrupt();
```

The [universal selector](https://developer.mozilla.org/en-US/docs/Web/CSS/Universal_selectors), `*`, selects all descendant elements. If you also want to interrupt the G element itself:

js

```
selection.interrupt().selectAll("*").interrupt();
```

## interrupt( _node_, _name_) [​](https://d3js.org/d3-transition/control-flow\#interrupt)

[Source](https://github.com/d3/d3-transition/blob/main/src/interrupt.js) · Interrupts the active transition of the specified _name_ on the specified _node_, and cancels any pending transitions with the specified _name_, if any. If a name is not specified, null is used. See also [_selection_.interrupt](https://d3js.org/d3-transition/control-flow#selection_interrupt).

## _transition_.end() [​](https://d3js.org/d3-transition/control-flow\#transition_end)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/end.js) · Returns a promise that resolves when every selected element finishes transitioning. If any element’s transition is cancelled or interrupted, the promise rejects.

## _transition_.on( _typenames_, _listener_) [​](https://d3js.org/d3-transition/control-flow\#transition_on)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/on.js) · Adds or removes a _listener_ to each selected element for the specified event _typenames_. The _typenames_ is one of the following string event types:

- `start` \- when the transition starts.
- `end` \- when the transition ends.
- `interrupt` \- when the transition is interrupted.
- `cancel` \- when the transition is cancelled.

See [The Life of a Transition](https://d3js.org/d3-transition/control-flow#the-life-of-a-transition) for more. Note that these are _not_ native DOM events as implemented by [_selection_.on](https://d3js.org/d3-selection/events#selection_on) and [_selection_.dispatch](https://d3js.org/d3-selection/events#selection_dispatch), but transition events!

The type may be optionally followed by a period ( `.`) and a name; the optional name allows multiple callbacks to be registered to receive events of the same type, such as `start.foo` and `start.bar`. To specify multiple typenames, separate typenames with spaces, such as `interrupt end` or `start.foo start.bar`.

When a specified transition event is dispatched on a selected node, the specified _listener_ will be invoked for the transitioning element, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. Listeners always see the latest datum for their element, but the index is a property of the selection and is fixed when the listener is assigned; to update the index, re-assign the listener.

If an event listener was previously registered for the same _typename_ on a selected element, the old listener is removed before the new listener is added. To remove a listener, pass null as the _listener_. To remove all listeners for a given name, pass null as the _listener_ and `.foo` as the _typename_, where `foo` is the name; to remove all listeners with no name, specify `.` as the _typename_.

If a _listener_ is not specified, returns the currently-assigned listener for the specified event _typename_ on the first (non-null) selected element, if any. If multiple typenames are specified, the first matching listener is returned.

## _transition_.each( _function_) [​](https://d3js.org/d3-transition/control-flow\#transition_each)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/each.js) · Invokes the specified _function_ for each selected element, passing in the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. This method can be used to invoke arbitrary code for each selected element, and is useful for creating a context to access parent and child data simultaneously. Equivalent to [_selection_.each](https://d3js.org/d3-selection/control-flow#selection_each).

## _transition_.call( _function_, ... _arguments_) [​](https://d3js.org/d3-transition/control-flow\#transition_call)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/call.js) · Invokes the specified _function_ exactly once, passing in this transition along with any optional _arguments_. Returns this transition. This is equivalent to invoking the function by hand but facilitates method chaining. For example, to set several attributes in a reusable function:

js

```
function color(transition, fill, stroke) {
  transition
      .style("fill", fill)
      .style("stroke", stroke);
}
```

Now say:

js

```
d3.selectAll("div").transition().call(color, "red", "blue");
```

This is equivalent to:

js

```
color(d3.selectAll("div").transition(), "red", "blue");
```

Equivalent to [_selection_.call](https://d3js.org/d3-selection/control-flow#selection_call).

## _transition_.empty() [​](https://d3js.org/d3-transition/control-flow\#transition_empty)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/empty.js) · Returns true if this transition contains no (non-null) elements. Equivalent to [_selection_.empty](https://d3js.org/d3-selection/control-flow#selection_empty).

## _transition_.nodes() [​](https://d3js.org/d3-transition/control-flow\#transition_nodes)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/nodes.js) · Returns an array of all (non-null) elements in this transition. Equivalent to [_selection_.nodes](https://d3js.org/d3-selection/control-flow#selection_nodes).

## _transition_.node() [​](https://d3js.org/d3-transition/control-flow\#transition_node)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/node.js) · Returns the first (non-null) element in this transition. If the transition is empty, returns null. Equivalent to [_selection_.node](https://d3js.org/d3-selection/control-flow#selection_node).

## _transition_.size() [​](https://d3js.org/d3-transition/control-flow\#transition_size)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/size.js) · Returns the total number of elements in this transition. Equivalent to [_selection_.size](https://d3js.org/d3-selection/control-flow#selection_size).

## D3 Treemap Layout
[Skip to content](https://d3js.org/d3-hierarchy/treemap#VPContent)

On this page

# Treemap [​](https://d3js.org/d3-hierarchy/treemap\#Treemap)

[![Treemap](https://raw.githubusercontent.com/d3/d3-hierarchy/main/img/treemap.png)](https://observablehq.com/@d3/treemap/2)

[Examples](https://observablehq.com/@d3/treemap/2) · Introduced by [Ben Shneiderman](http://www.cs.umd.edu/hcil/treemap-history/) in 1991, a **treemap** recursively subdivides area into rectangles according to each node’s associated value. D3’s treemap implementation supports an extensible [tiling method](https://d3js.org/d3-hierarchy/treemap#treemap_tile): the default [squarified](https://d3js.org/d3-hierarchy/treemap#treemapSquarify) method seeks to generate rectangles with a [golden](https://en.wikipedia.org/wiki/Golden_ratio) aspect ratio; this offers better readability and size estimation than [slice-and-dice](https://d3js.org/d3-hierarchy/treemap#treemapSliceDice), which simply alternates between horizontal and vertical subdivision by depth.

## treemap() [​](https://d3js.org/d3-hierarchy/treemap\#treemap)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · Creates a new treemap layout with default settings.

## _treemap_( _root_) [​](https://d3js.org/d3-hierarchy/treemap\#_treemap)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · Lays out the specified _root_ [hierarchy](https://d3js.org/d3-hierarchy/hierarchy), assigning the following properties on _root_ and its descendants:

- _node_.x0 - the left edge of the rectangle
- _node_.y0 - the top edge of the rectangle
- _node_.x1 - the right edge of the rectangle
- _node_.y1 - the bottom edge of the rectangle

You must call [_root_.sum](https://d3js.org/d3-hierarchy/hierarchy#node_sum) before passing the hierarchy to the treemap layout. You probably also want to call [_root_.sort](https://d3js.org/d3-hierarchy/hierarchy#node_sort) to order the hierarchy before computing the layout.

## _treemap_.tile( _tile_) [​](https://d3js.org/d3-hierarchy/treemap\#treemap_tile)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · If _tile_ is specified, sets the [tiling method](https://d3js.org/d3-hierarchy/treemap#treemap-tiling) to the specified function and returns this treemap layout. If _tile_ is not specified, returns the current tiling method, which defaults to [treemapSquarify](https://d3js.org/d3-hierarchy/treemap#treemapSquarify) with the golden ratio.

## _treemap_.size( _size_) [​](https://d3js.org/d3-hierarchy/treemap\#treemap_size)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · If _size_ is specified, sets this treemap layout’s size to the specified two-element array of numbers \[ _width_, _height_\] and returns this treemap layout. If _size_ is not specified, returns the current size, which defaults to \[1, 1\].

## _treemap_.round( _round_) [​](https://d3js.org/d3-hierarchy/treemap\#treemap_round)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · If _round_ is specified, enables or disables rounding according to the given boolean and returns this treemap layout. If _round_ is not specified, returns the current rounding state, which defaults to false.

## _treemap_.padding( _padding_) [​](https://d3js.org/d3-hierarchy/treemap\#treemap_padding)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · If _padding_ is specified, sets the [inner](https://d3js.org/d3-hierarchy/treemap#treemap_paddingInner) and [outer](https://d3js.org/d3-hierarchy/treemap#treemap_paddingOuter) padding to the specified number or function and returns this treemap layout. If _padding_ is not specified, returns the current inner padding function.

## _treemap_.paddingInner( _padding_) [​](https://d3js.org/d3-hierarchy/treemap\#treemap_paddingInner)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · If _padding_ is specified, sets the inner padding to the specified number or function and returns this treemap layout. If _padding_ is not specified, returns the current inner padding function, which defaults to the constant zero. If _padding_ is a function, it is invoked for each node with children, being passed the current node. The inner padding is used to separate a node’s adjacent children.

## _treemap_.paddingOuter( _padding_) [​](https://d3js.org/d3-hierarchy/treemap\#treemap_paddingOuter)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · If _padding_ is specified, sets the [top](https://d3js.org/d3-hierarchy/treemap#treemap_paddingTop), [right](https://d3js.org/d3-hierarchy/treemap#treemap_paddingRight), [bottom](https://d3js.org/d3-hierarchy/treemap#treemap_paddingBottom) and [left](https://d3js.org/d3-hierarchy/treemap#treemap_paddingLeft) padding to the specified number or function and returns this treemap layout. If _padding_ is not specified, returns the current top padding function.

## _treemap_.paddingTop( _padding_) [​](https://d3js.org/d3-hierarchy/treemap\#treemap_paddingTop)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · If _padding_ is specified, sets the top padding to the specified number or function and returns this treemap layout. If _padding_ is not specified, returns the current top padding function, which defaults to the constant zero. If _padding_ is a function, it is invoked for each node with children, being passed the current node. The top padding is used to separate the top edge of a node from its children.

## _treemap_.paddingRight( _padding_) [​](https://d3js.org/d3-hierarchy/treemap\#treemap_paddingRight)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · If _padding_ is specified, sets the right padding to the specified number or function and returns this treemap layout. If _padding_ is not specified, returns the current right padding function, which defaults to the constant zero. If _padding_ is a function, it is invoked for each node with children, being passed the current node. The right padding is used to separate the right edge of a node from its children.

## _treemap_.paddingBottom( _padding_) [​](https://d3js.org/d3-hierarchy/treemap\#treemap_paddingBottom)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · If _padding_ is specified, sets the bottom padding to the specified number or function and returns this treemap layout. If _padding_ is not specified, returns the current bottom padding function, which defaults to the constant zero. If _padding_ is a function, it is invoked for each node with children, being passed the current node. The bottom padding is used to separate the bottom edge of a node from its children.

## _treemap_.paddingLeft( _padding_) [​](https://d3js.org/d3-hierarchy/treemap\#treemap_paddingLeft)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/index.js) · If _padding_ is specified, sets the left padding to the specified number or function and returns this treemap layout. If _padding_ is not specified, returns the current left padding function, which defaults to the constant zero. If _padding_ is a function, it is invoked for each node with children, being passed the current node. The left padding is used to separate the left edge of a node from its children.

## Treemap tiling [​](https://d3js.org/d3-hierarchy/treemap\#treemap-tiling)

Several built-in tiling methods are provided for use with [_treemap_.tile](https://d3js.org/d3-hierarchy/treemap#treemap_tile).

### treemapBinary( _node_, _x0_, _y0_, _x1_, _y1_) [​](https://d3js.org/d3-hierarchy/treemap\#treemapBinary)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/binary.js) · Recursively partitions the specified _nodes_ into an approximately-balanced binary tree, choosing horizontal partitioning for wide rectangles and vertical partitioning for tall rectangles.

### treemapDice( _node_, _x0_, _y0_, _x1_, _y1_) [​](https://d3js.org/d3-hierarchy/treemap\#treemapDice)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/dice.js) · Divides the rectangular area specified by _x0_, _y0_, _x1_, _y1_ horizontally according the value of each of the specified _node_’s children. The children are positioned in order, starting with the left edge ( _x0_) of the given rectangle. If the sum of the children’s values is less than the specified _node_’s value ( _i.e._, if the specified _node_ has a non-zero internal value), the remaining empty space will be positioned on the right edge ( _x1_) of the given rectangle.

### treemapSlice( _node_, _x0_, _y0_, _x1_, _y1_) [​](https://d3js.org/d3-hierarchy/treemap\#treemapSlice)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/slice.js) · Divides the rectangular area specified by _x0_, _y0_, _x1_, _y1_ vertically according the value of each of the specified _node_’s children. The children are positioned in order, starting with the top edge ( _y0_) of the given rectangle. If the sum of the children’s values is less than the specified _node_’s value ( _i.e._, if the specified _node_ has a non-zero internal value), the remaining empty space will be positioned on the bottom edge ( _y1_) of the given rectangle.

### treemapSliceDice( _node_, _x0_, _y0_, _x1_, _y1_) [​](https://d3js.org/d3-hierarchy/treemap\#treemapSliceDice)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/sliceDice.js) · If the specified _node_ has odd depth, delegates to [treemapSlice](https://d3js.org/d3-hierarchy/treemap#treemapSlice); otherwise delegates to [treemapDice](https://d3js.org/d3-hierarchy/treemap#treemapDice).

### treemapSquarify( _node_, _x0_, _y0_, _x1_, _y1_) [​](https://d3js.org/d3-hierarchy/treemap\#treemapSquarify)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/squarify.js) · Implements the [squarified treemap](https://www.win.tue.nl/~vanwijk/stm.pdf) algorithm by Bruls _et al._, which seeks to produce rectangles of a given [aspect ratio](https://d3js.org/d3-hierarchy/treemap#squarify_ratio).

### treemapResquarify( _node_, _x0_, _y0_, _x1_, _y1_) [​](https://d3js.org/d3-hierarchy/treemap\#treemapResquarify)

[Examples](https://observablehq.com/@d3/animated-treemap) · [Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/resquarify.js) · Like [treemapSquarify](https://d3js.org/d3-hierarchy/treemap#treemapSquarify), except preserves the topology (node adjacencies) of the previous layout computed by d3.treemapResquarify, if there is one and it used the same [target aspect ratio](https://d3js.org/d3-hierarchy/treemap#squarify_ratio). This tiling method is good for animating changes to treemaps because it only changes node sizes and not their relative positions, thus avoiding distracting shuffling and occlusion. The downside of a stable update, however, is a suboptimal layout for subsequent updates: only the first layout uses the Bruls _et al._ squarified algorithm.

### _squarify_.ratio( _ratio_) [​](https://d3js.org/d3-hierarchy/treemap\#squarify_ratio)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/treemap/squarify.js) · Specifies the desired aspect ratio of the generated rectangles. The _ratio_ must be specified as a number greater than or equal to one. Note that the orientation of the generated rectangles (tall or wide) is not implied by the ratio; for example, a ratio of two will attempt to produce a mixture of rectangles whose _width_: _height_ ratio is either 2:1 or 1:2. (However, you can approximately achieve this result by generating a square treemap at different dimensions, and then [stretching the treemap](https://observablehq.com/@d3/stretched-treemap) to the desired aspect ratio.) Furthermore, the specified _ratio_ is merely a hint to the tiling algorithm; the rectangles are not guaranteed to have the specified aspect ratio. If not specified, the aspect ratio defaults to the golden ratio, φ = (1 + sqrt(5)) / 2, per [Kong _et al._](http://vis.stanford.edu/papers/perception-treemaps)

## Conic Projections Overview
[Skip to content](https://d3js.org/d3-geo/conic#VPContent)

On this page

# Conic projections [​](https://d3js.org/d3-geo/conic\#conic-projections)

Conic projections project the sphere onto a cone, and then unroll the cone onto the plane. Conic projections have [two standard parallels](https://d3js.org/d3-geo/conic#conic_parallels).

## _conic_.parallels( _parallels_) [​](https://d3js.org/d3-geo/conic\#conic_parallels)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/conic.js) · The [two standard parallels](https://en.wikipedia.org/wiki/Map_projection#Conic) that define the map layout in conic projections.

## geoConicConformal() [​](https://d3js.org/d3-geo/conic\#geoConicConformal)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/conicConformal.js) · The conic conformal projection. The parallels default to \[30°, 30°\] resulting in flat top.

## geoConicEqualArea() [​](https://d3js.org/d3-geo/conic\#geoConicEqualArea)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/conicEqualArea.js) · The Albers’ equal-area conic projection.

## geoConicEquidistant() [​](https://d3js.org/d3-geo/conic\#geoConicEquidistant)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/conicEquidistant.js) · The conic equidistant projection.

## geoAlbers() [​](https://d3js.org/d3-geo/conic\#geoAlbers)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/albers.js) · The Albers’ equal area-conic projection. This is a U.S.-centric configuration of [geoConicEqualArea](https://d3js.org/d3-geo/conic#geoConicEqualArea).

## geoAlbersUsa() [​](https://d3js.org/d3-geo/conic\#geoAlbersUsa)

[Source](https://github.com/d3/d3-geo/blob/main/src/projection/albersUsa.js) · This is a U.S.-centric composite projection of three [geoConicEqualArea](https://d3js.org/d3-geo/conic#geoConicEqualArea) projections: [geoAlbers](https://d3js.org/d3-geo/conic#geoAlbers) is used for the lower forty-eight states, and separate conic equal-area projections are used for Alaska and Hawaii. The scale for Alaska is diminished: it is projected at 0.35× its true relative area. See [Albers USA with Territories](https://www.npmjs.com/package/geo-albers-usa-territories) for an extension to all US territories, and [d3-composite-projections](http://geoexamples.com/d3-composite-projections/) for more examples.

The constituent projections have fixed clip, center and rotation, and thus this projection does not support [_projection_.center](https://d3js.org/d3-geo/projection#projection_center), [_projection_.rotate](https://d3js.org/d3-geo/projection#projection_rotate), [_projection_.clipAngle](https://d3js.org/d3-geo/projection#projection_clipAngle), or [_projection_.clipExtent](https://d3js.org/d3-geo/projection#projection_clipExtent).

## D3 Transition Selection
[Skip to content](https://d3js.org/d3-transition/selecting#VPContent)

On this page

# Selecting elements [​](https://d3js.org/d3-transition/selecting\#selecting-elements)

Transitions are derived from [selections](https://d3js.org/d3-selection) via [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition). You can also create a transition on the document root element using [d3.transition](https://d3js.org/d3-transition/selecting#transition).

## _selection_.transition( _name_) [​](https://d3js.org/d3-transition/selecting\#selection_transition)

[Source](https://github.com/d3/d3-transition/blob/main/src/selection/transition.js) · Returns a new transition on the given _selection_ with the specified _name_. If a _name_ is not specified, null is used. The new transition is only exclusive with other transitions of the same name.

If the _name_ is a [transition](https://d3js.org/d3-transition/selecting#transition) instance, the returned transition has the same id and name as the specified transition. If a transition with the same id already exists on a selected element, the existing transition is returned for that element. Otherwise, the timing of the returned transition is inherited from the existing transition of the same id on the nearest ancestor of each selected element. Thus, this method can be used to synchronize a transition across multiple selections, or to re-select a transition for specific elements and modify its configuration. For example:

js

```
const t = d3.transition()
    .duration(750)
    .ease(d3.easeLinear);

d3.selectAll(".apple").transition(t)
    .style("fill", "red");

d3.selectAll(".orange").transition(t)
    .style("fill", "orange");
```

If the specified _transition_ is not found on a selected node or its ancestors (such as if the transition [already ended](https://d3js.org/d3-transition/control-flow#the-life-of-a-transition)), the default timing parameters are used; however, in a future release, this will likely be changed to throw an error. See [#59](https://github.com/d3/d3-transition/issues/59).

## transition( _name_) [​](https://d3js.org/d3-transition/selecting\#transition)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/index.js) · Returns a new transition on the root element, `document.documentElement`, with the specified _name_. If a _name_ is not specified, null is used. The new transition is only exclusive with other transitions of the same name. The _name_ may also be a [transition](https://d3js.org/d3-transition/selecting#transition) instance; see [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition). This method is equivalent to:

js

```
d3.selection()
  .transition(name)
```

This function can also be used to test for transitions ( `instanceof d3.transition`) or to extend the transition prototype.

## _transition_.select( _selector_) [​](https://d3js.org/d3-transition/selecting\#transition_select)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/select.js) · For each selected element, selects the first descendant element that matches the specified _selector_ string, if any, and returns a transition on the resulting selection. The _selector_ may be specified either as a selector string or a function. If a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The new transition has the same id, name and timing as this transition; however, if a transition with the same id already exists on a selected element, the existing transition is returned for that element.

This method is equivalent to deriving the selection for this transition via [_transition_.selection](https://d3js.org/d3-transition/selecting#transition_selection), creating a subselection via [_selection_.select](https://d3js.org/d3-selection/selecting#selection_select), and then creating a new transition via [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition):

js

```
transition
  .selection()
  .select(selector)
  .transition(transition)
```

## _transition_.selectAll(selector) [​](https://d3js.org/d3-transition/selecting\#transition_selectAll)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/selectAll.js) · For each selected element, selects all descendant elements that match the specified _selector_ string, if any, and returns a transition on the resulting selection. The _selector_ may be specified either as a selector string or a function. If a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The new transition has the same id, name and timing as this transition; however, if a transition with the same id already exists on a selected element, the existing transition is returned for that element.

This method is equivalent to deriving the selection for this transition via [_transition_.selection](https://d3js.org/d3-transition/selecting#transition_selection), creating a subselection via [_selection_.selectAll](https://d3js.org/d3-selection/selecting#selection_selectAll), and then creating a new transition via [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition):

js

```
transition
  .selection()
  .selectAll(selector)
  .transition(transition)
```

## _transition_.selectChild( _selector_) [​](https://d3js.org/d3-transition/selecting\#transition_selectChild)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/select.js) · For each selected element, selects the first child element that matches the specified _selector_ string, if any, and returns a transition on the resulting selection. The _selector_ may be specified either as a selector string or a function. If a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The new transition has the same id, name and timing as this transition; however, if a transition with the same id already exists on a selected element, the existing transition is returned for that element.

This method is equivalent to deriving the selection for this transition via [_transition_.selection](https://d3js.org/d3-transition/selecting#transition_selection), creating a subselection via [_selection_.selectChild](https://d3js.org/d3-selection/selecting#selection_selectChild), and then creating a new transition via [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition):

js

```
transition
  .selection()
  .selectChild(selector)
  .transition(transition)
```

## _transition_.selectChildren( _selector_) [​](https://d3js.org/d3-transition/selecting\#transition_selectChildren)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/selectAll.js) · For each selected element, selects all children that match the specified _selector_ string, if any, and returns a transition on the resulting selection. The _selector_ may be specified either as a selector string or a function. If a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The new transition has the same id, name and timing as this transition; however, if a transition with the same id already exists on a selected element, the existing transition is returned for that element.

This method is equivalent to deriving the selection for this transition via [_transition_.selection](https://d3js.org/d3-transition/selecting#transition_selection), creating a subselection via [_selection_.selectChildren](https://d3js.org/d3-selection/selecting#selection_selectChildren), and then creating a new transition via [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition):

js

```
transition
  .selection()
  .selectChildren(selector)
  .transition(transition)
```

## _transition_.filter( _filter_) [​](https://d3js.org/d3-transition/selecting\#transition_filter)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/filter.js) · For each selected element, selects only the elements that match the specified _filter_, and returns a transition on the resulting selection. The _filter_ may be specified either as a selector string or a function. If a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The new transition has the same id, name and timing as this transition; however, if a transition with the same id already exists on a selected element, the existing transition is returned for that element.

This method is equivalent to deriving the selection for this transition via [_transition_.selection](https://d3js.org/d3-transition/selecting#transition_selection), creating a subselection via [_selection_.filter](https://d3js.org/d3-selection/selecting#selection_filter), and then creating a new transition via [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition):

js

```
transition
  .selection()
  .filter(filter)
  .transition(transition)
```

## _transition_.merge( _other_) [​](https://d3js.org/d3-transition/selecting\#transition_merge)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/merge.js) · Returns a new transition merging this transition with the specified _other_ transition, which must have the same id as this transition. The returned transition has the same number of groups, the same parents, the same name and the same id as this transition. Any missing (null) elements in this transition are filled with the corresponding element, if present (not null), from the _other_ transition.

This method is equivalent to deriving the selection for this transition via [_transition_.selection](https://d3js.org/d3-transition/selecting#transition_selection), merging with the selection likewise derived from the _other_ transition via [_selection_.merge](https://d3js.org/d3-selection/joining#selection_merge), and then creating a new transition via [_selection_.transition](https://d3js.org/d3-transition/selecting#selection_transition):

js

```
transition
  .selection()
  .merge(other.selection())
  .transition(transition)
```

## _transition_.transition() [​](https://d3js.org/d3-transition/selecting\#transition_transition)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/transition.js) · Returns a new transition on the same selected elements as this transition, scheduled to start when this transition ends. The new transition inherits a reference time equal to this transition’s time plus its [delay](https://d3js.org/d3-transition/timing#transition_delay) and [duration](https://d3js.org/d3-transition/timing#transition_duration). The new transition also inherits this transition’s name, duration, and [easing](https://d3js.org/d3-transition/timing#transition_ease). This method can be used to schedule a sequence of chained transitions. For example:

js

```
d3.selectAll(".apple")
  .transition() // First fade to green.
    .style("fill", "green")
  .transition() // Then red.
    .style("fill", "red")
  .transition() // Wait one second. Then brown, and remove.
    .delay(1000)
    .style("fill", "brown")
    .remove();
```

The delay for each transition is relative to its previous transition. Thus, in the above example, apples will stay red for one second before the last transition to brown starts.

## _transition_.selection() [​](https://d3js.org/d3-transition/selecting\#transition_selection)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/selection.js) · Returns the [selection](https://d3js.org/d3-selection/selecting#selection) corresponding to this transition.

## active(node, name) [​](https://d3js.org/d3-transition/selecting\#active)

[Examples](https://observablehq.com/@d3/chained-transitions) · [Source](https://github.com/d3/d3-transition/blob/main/src/active.js) · Returns the active transition on the specified _node_ with the specified _name_, if any. If no _name_ is specified, null is used. Returns null if there is no such active transition on the specified node. This method is useful for creating chained transitions. For example, to initiate disco mode:

js

```
d3.selectAll("circle").transition()
    .delay((d, i) => i * 50)
    .on("start", function repeat() {
        d3.active(this)
            .style("fill", "red")
          .transition()
            .style("fill", "green")
          .transition()
            .style("fill", "blue")
          .transition()
            .on("start", repeat);
      });
```

## D3.js Link Force
[Skip to content](https://d3js.org/d3-force/link#VPContent)

On this page

# Link force [​](https://d3js.org/d3-force/link\#link-force)

[Fork ↗︎](https://observablehq.com/@d3/force-directed-lattice)

The link force pushes linked nodes together or apart according to the desired [link distance](https://d3js.org/d3-force/link#link_distance). The strength of the force is proportional to the difference between the linked nodes’ distance and the target distance, similar to a spring force.

## forceLink( _links_) [​](https://d3js.org/d3-force/link\#forceLink)

[Source](https://github.com/d3/d3-force/blob/main/src/link.js) · Creates a new link force with the specified _links_ and default parameters. If _links_ is not specified, it defaults to the empty array.

WARNING

This function is impure; it may mutate the passed-in _links_. See [_link_.links](https://d3js.org/d3-force/link#link_links).

js

```
const link = d3.forceLink(links).id((d) => d.id);
```

## _link_.links( _links_) [​](https://d3js.org/d3-force/link\#link_links)

[Source](https://github.com/d3/d3-force/blob/main/src/link.js) · If _links_ is specified, sets the array of links associated with this force, recomputes the [distance](https://d3js.org/d3-force/link#link_distance) and [strength](https://d3js.org/d3-force/link#link_strength) parameters for each link, and returns this force. If _links_ is not specified, returns the current array of links, which defaults to the empty array.

Each link is an object with the following properties:

- `source` \- the link’s source node; see [_simulation_.nodes](https://d3js.org/d3-force/simulation#simulation_nodes)
- `target` \- the link’s target node; see [_simulation_.nodes](https://d3js.org/d3-force/simulation#simulation_nodes)
- `index` \- the zero-based index into _links_, assigned by this method

For convenience, a link’s source and target properties may be initialized using numeric or string identifiers rather than object references; see [_link_.id](https://d3js.org/d3-force/link#link_id).

WARNING

This function is impure; it may mutate the passed-in _links_ when the link force is [initialized](https://d3js.org/d3-force/simulation#force_initialize) (or re-initialized, as when the nodes or links change). Any _link_.source or _link_.target property which is not an object is replaced by an object reference to the corresponding _node_ with the given identifier.

If the specified array of _links_ is modified, such as when links are added to or removed from the simulation, this method must be called again with the new (or changed) array to notify the force of the change; the force does not make a defensive copy of the specified array.

## _link_.id( _id_) [​](https://d3js.org/d3-force/link\#link_id)

[Source](https://github.com/d3/d3-force/blob/main/src/link.js) · If _id_ is specified, sets the node id accessor to the specified function and returns this force. If _id_ is not specified, returns the current node id accessor, which defaults to the numeric _node_.index:

js

```
function id(d) {
  return d.index;
}
```

The default id accessor allows each link’s source and target to be specified as a zero-based index into the [nodes](https://d3js.org/d3-force/simulation#simulation_nodes) array. For example:

js

```
const nodes = [\
  {"id": "Alice"},\
  {"id": "Bob"},\
  {"id": "Carol"}\
];

const links = [\
  {"source": 0, "target": 1}, // Alice → Bob\
  {"source": 1, "target": 2} // Bob → Carol\
];
```

Now consider a different id accessor that returns a string:

js

```
function id(d) {
  return d.id;
}
```

With this accessor, you can use named sources and targets:

js

```
const nodes = [\
  {"id": "Alice"},\
  {"id": "Bob"},\
  {"id": "Carol"}\
];

const links = [\
  {"source": "Alice", "target": "Bob"},\
  {"source": "Bob", "target": "Carol"}\
];
```

This is particularly useful when representing graphs in JSON, as JSON does not allow references. See [this example](https://observablehq.com/@d3/force-directed-graph/2).

The id accessor is invoked for each node whenever the force is initialized, as when the [nodes](https://d3js.org/d3-force/simulation#simulation_nodes) or [links](https://d3js.org/d3-force/link#link_links) change, being passed the node and its zero-based index.

## _link_.distance( _distance_) [​](https://d3js.org/d3-force/link\#link_distance)

[Source](https://github.com/d3/d3-force/blob/main/src/link.js) · If _distance_ is specified, sets the distance accessor to the specified number or function, re-evaluates the distance accessor for each link, and returns this force. If _distance_ is not specified, returns the current distance accessor, which defaults to:

js

```
function distance() {
  return 30;
}
```

The distance accessor is invoked for each [link](https://d3js.org/d3-force/link#link_links), being passed the _link_ and its zero-based _index_. The resulting number is then stored internally, such that the distance of each link is only recomputed when the force is initialized or when this method is called with a new _distance_, and not on every application of the force.

## _link_.strength( _strength_) [​](https://d3js.org/d3-force/link\#link_strength)

[Source](https://github.com/d3/d3-force/blob/main/src/link.js) · If _strength_ is specified, sets the strength accessor to the specified number or function, re-evaluates the strength accessor for each link, and returns this force. If _strength_ is not specified, returns the current strength accessor, which defaults to:

js

```
function strength(link) {
  return 1 / Math.min(count(link.source), count(link.target));
}
```

Where _count_( _node_) is a function that returns the number of links with the given node as a source or target. This default was chosen because it automatically reduces the strength of links connected to heavily-connected nodes, improving stability.

The strength accessor is invoked for each [link](https://d3js.org/d3-force/link#link_links), being passed the _link_ and its zero-based _index_. The resulting number is then stored internally, such that the strength of each link is only recomputed when the force is initialized or when this method is called with a new _strength_, and not on every application of the force.

## _link_.iterations( _iterations_) [​](https://d3js.org/d3-force/link\#link_iterations)

[Source](https://github.com/d3/d3-force/blob/main/src/link.js) · If _iterations_ is specified, sets the number of iterations per application to the specified number and returns this force. If _iterations_ is not specified, returns the current iteration count which defaults to 1. Increasing the number of iterations greatly increases the rigidity of the constraint and is useful for [complex structures such as lattices](https://observablehq.com/@d3/force-directed-lattice), but also increases the runtime cost to evaluate the force.

## D3.js Time Functions
[Skip to content](https://d3js.org/d3-time#VPContent)

On this page

# d3-time [​](https://d3js.org/d3-time\#d3-time)

When visualizing time series data, analyzing temporal patterns, or working with time in general, the irregularities of conventional time units quickly become apparent. In the [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar), for example, most months have 31 days but some have 28, 29 or 30; most years have 365 days but [leap years](https://en.wikipedia.org/wiki/Leap_year) have 366; and with [daylight saving](https://en.wikipedia.org/wiki/Daylight_saving_time), most days have 24 hours but some have 23 or 25. Adding to complexity, daylight saving conventions vary around the world.

As a result of these temporal peculiarities, it can be difficult to perform seemingly-trivial tasks. For example, if you want to compute the number of days that have passed between two dates, you can’t simply subtract and divide by 24 hours (86,400,000 ms):

js

```
const start = new Date(2015, 02, 01); // 2015-03-01T00:00
const end = new Date(2015, 03, 01); // 2015-04-01T00:00
const days = (end - start) / 864e5; // 30.958333333333332, oops! 🤯
```

You can, however, use [d3.timeDay](https://d3js.org/d3-time#timeDay). [count](https://d3js.org/d3-time#interval_count):

js

```
d3.timeDay.count(start, end) // 31 😌
```

The [day](https://d3js.org/d3-time#timeDay) [interval](https://d3js.org/d3-time#timeInterval) is one of several provided by d3-time. Each interval represents a conventional unit of time — [hours](https://d3js.org/d3-time#timeHour), [weeks](https://d3js.org/d3-time#timeWeek), [months](https://d3js.org/d3-time#timeMonth), _etc._ — and has methods to calculate boundary dates. For example, [d3.timeDay](https://d3js.org/d3-time#timeDay) computes midnight (typically 12:00 AM local time) of the corresponding day. In addition to [rounding](https://d3js.org/d3-time#interval_round) and [counting](https://d3js.org/d3-time#interval_count), intervals can also be used to generate arrays of boundary dates. For example, to compute each Sunday in the current month:

js

```
const start = d3.timeMonth.floor(new Date(2015, 0, 15)); // 2015-01-01T00:00
const stop = d3.timeMonth.ceil(new Date(2015, 0, 15)); // 2015-02-01T00:00
const weeks = d3.timeWeek.range(start, stop); // [2015-01-04T00:00, 2015-01-11T00:00, 2015-01-18T00:00, 2015-01-25T00:00]
```

The d3-time module does not implement its own calendaring system; it merely implements a convenient API for calendar math on top of ECMAScript [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date). Thus, it ignores leap seconds and can only work with the local time zone and [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) (UTC).

This module is used by D3’s time scales to generate sensible ticks, by D3’s time format, and can also be used directly to do things like [calendar layouts](https://observablehq.com/@d3/calendar/2).

## _interval_( _date_) [​](https://d3js.org/d3-time\#_interval)

js

```
d3.utcMonday() // the latest preceding Monday, UTC time
```

[Source](https://github.com/d3/d3-time/blob/main/src/interval.js) · Equivalent to [_interval_.floor](https://d3js.org/d3-time#interval_floor), except if _date_ is not specified, it defaults to the current time. For example, [d3.timeYear](https://d3js.org/d3-time#timeYear)( _date_) and d3.timeYear.floor( _date_) are equivalent.

## _interval_.floor( _date_) [​](https://d3js.org/d3-time\#interval_floor)

js

```
d3.utcMonday.floor(new Date()) // the latest preceding Monday, UTC time
```

[Source](https://github.com/d3/d3-time/blob/main/src/interval.js) · Returns a new date representing the latest interval boundary date before or equal to _date_. For example, [d3.timeDay](https://d3js.org/d3-time#timeDay).floor( _date_) typically returns 12:00 AM local time on the given _date_.

This method is idempotent: if the specified _date_ is already floored to the current interval, a new date with an identical time is returned. Furthermore, the returned date is the minimum expressible value of the associated interval, such that _interval_.floor( _interval_.floor( _date_) \- 1) returns the preceding interval boundary date.

Note that the `==` and `===` operators do not compare by value with [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) objects, and thus you cannot use them to tell whether the specified _date_ has already been floored. Instead, coerce to a number and then compare:

js

```
// Returns true if the specified date is a day boundary.
function isDay(date) {
  return +d3.timeDay.floor(date) === +date;
}
```

This is more reliable than testing whether the time is 12:00 AM, as in some time zones midnight may not exist due to daylight saving.

## _interval_.round( _date_) [​](https://d3js.org/d3-time\#interval_round)

js

```
d3.utcMonday.round(new Date()) // the previous or following Monday, whichever is closer
```

[Source](https://github.com/d3/d3-time/blob/main/src/interval.js) · Returns a new date representing the closest interval boundary date to _date_. For example, [d3.timeDay](https://d3js.org/d3-time#timeDay).round( _date_) typically returns 12:00 AM local time on the given _date_ if it is on or before noon, and 12:00 AM of the following day if it is after noon.

This method is idempotent: if the specified _date_ is already rounded to the current interval, a new date with an identical time is returned.

## _interval_.ceil( _date_) [​](https://d3js.org/d3-time\#interval_ceil)

js

```
d3.utcMonday.ceil(new Date()) // the following Monday
```

[Source](https://github.com/d3/d3-time/blob/main/src/interval.js) · Returns a new date representing the earliest interval boundary date after or equal to _date_. For example, [d3.timeDay](https://d3js.org/d3-time#timeDay).ceil( _date_) typically returns 12:00 AM local time on the date following the given _date_.

This method is idempotent: if the specified _date_ is already ceilinged to the current interval, a new date with an identical time is returned. Furthermore, the returned date is the maximum expressible value of the associated interval, such that _interval_.ceil( _interval_.ceil( _date_) \+ 1) returns the following interval boundary date.

## _interval_.offset( _date_, _step_) [​](https://d3js.org/d3-time\#interval_offset)

js

```
d3.utcDay.offset(new Date(), 1) // the same time tomorrow
```

[Source](https://github.com/d3/d3-time/blob/main/src/interval.js) · Returns a new date equal to _date_ plus _step_ intervals. If _step_ is not specified it defaults to 1. If _step_ is negative, then the returned date will be before the specified _date_; if _step_ is zero, then a copy of the specified _date_ is returned; if _step_ is not an integer, it is [floored](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor). This method does not round the specified _date_ to the interval. For example, if _date_ is today at 5:34 PM, then [d3.timeDay](https://d3js.org/d3-time#timeDay).offset( _date_, 1) returns 5:34 PM tomorrow (even if daylight saving changes!).

## _interval_.range( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#interval_range)

js

```
d3.utcDay.range(new Date("2014-01-01"), new Date("2015-01-01")) // every day in 2014
```

[Source](https://github.com/d3/d3-time/blob/main/src/interval.js) · Returns an array of dates representing every interval boundary after or equal to _start_ (inclusive) and before _stop_ (exclusive). If _step_ is specified, then every _step_ th boundary will be returned; for example, for the [d3.timeDay](https://d3js.org/d3-time#timeDay) interval a _step_ of 2 will return every other day. If _step_ is not an integer, it is [floored](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor).

The first date in the returned array is the earliest boundary after or equal to _start_; subsequent dates are [offset](https://d3js.org/d3-time#interval_offset) by _step_ intervals and [floored](https://d3js.org/d3-time#interval_floor). Thus, two overlapping ranges may be consistent. For example, this range contains odd days:

js

```
d3.timeDay.range(new Date(2015, 0, 1), new Date(2015, 0, 7), 2) // [2015-01-01T00:00, 2015-01-03T00:00, 2015-01-05T00:00]
```

While this contains even days:

js

```
d3.timeDay.range(new Date(2015, 0, 2), new Date(2015, 0, 8), 2) // [2015-01-02T00:00, 2015-01-04T00:00, 2015-01-06T00:00]
```

To make ranges consistent when a _step_ is specified, use [_interval_.every](https://d3js.org/d3-time#interval_every) instead.

For convenience, aliases for _interval_.range are also provided as plural forms of the corresponding interval, such as [utcMondays](https://d3js.org/d3-time#utcMondays).

## _interval_.filter( _test_) [​](https://d3js.org/d3-time\#interval_filter)

[Source](https://github.com/d3/d3-time/blob/main/src/interval.js) · Returns a new interval that is a filtered subset of this interval using the specified _test_ function. The _test_ function is passed a date and should return true if and only if the specified date should be considered part of the interval. For example, to create an interval that returns the 1st, 11th, 21th and 31th (if it exists) of each month:

js

```
d3.timeDay.filter((d) => (d.getDate() - 1) % 10 === 0)
```

The returned filtered interval does not support [_interval_.count](https://d3js.org/d3-time#interval_count). See also [_interval_.every](https://d3js.org/d3-time#interval_every).

## _interval_.every( _step_) [​](https://d3js.org/d3-time\#interval_every)

js

```
d3.unixDay.every(3)
```

[Source](https://github.com/d3/d3-time/blob/main/src/interval.js) · Returns a [filtered](https://d3js.org/d3-time#interval_filter) view of this interval representing every _step_ th date. The meaning of _step_ is dependent on this interval’s parent interval as defined by the field function. For example, [d3.timeMinute](https://d3js.org/d3-time#timeMinute).every(15) returns an interval representing every fifteen minutes, starting on the hour: :00, :15, :30, :45, _etc._ Note that for some intervals, the resulting dates may not be uniformly-spaced; [d3.timeDay](https://d3js.org/d3-time#timeDay)’s parent interval is [d3.timeMonth](https://d3js.org/d3-time#timeMonth), and thus the interval number resets at the start of each month. If _step_ is not valid, returns null. If _step_ is one, returns this interval.

This method can be used in conjunction with [_interval_.range](https://d3js.org/d3-time#interval_range) to ensure that two overlapping ranges are consistent. For example, this range contains odd days:

js

```
d3.timeDay.every(2).range(new Date(2015, 0, 1), new Date(2015, 0, 7)) // [2015-01-01T00:00, 2015-01-03T00:00, 2015-01-05T00:00]
```

As does this one:

js

```
d3.timeDay.every(2).range(new Date(2015, 0, 2), new Date(2015, 0, 8)) // [2015-01-03T00:00, 2015-01-05T00:00, 2015-01-07T00:00]
```

The returned filtered interval does not support [_interval_.count](https://d3js.org/d3-time#interval_count). See also [_interval_.filter](https://d3js.org/d3-time#interval_filter).

## _interval_.count( _start_, _end_) [​](https://d3js.org/d3-time\#interval_count)

[Source](https://github.com/d3/d3-time/blob/main/src/interval.js) · Returns the number of interval boundaries after _start_ (exclusive) and before or equal to _end_ (inclusive). Note that this behavior is slightly different than [_interval_.range](https://d3js.org/d3-time#interval_range) because its purpose is to return the zero-based number of the specified _end_ date relative to the specified _start_ date. For example, to compute the current zero-based day-of-year number:

js

```
d3.timeDay.count(d3.timeYear(now), now) // 177
```

Likewise, to compute the current zero-based week-of-year number for weeks that start on Sunday:

js

```
d3.timeSunday.count(d3.timeYear(now), now) // 25
```

## timeInterval( _floor_, _offset_, _count_, _field_) [​](https://d3js.org/d3-time\#timeInterval)

js

```
const utcDay = d3.timeInterval(
  (date) => date.setUTCHours(0, 0, 0, 0), // floor
  (date, step) => date.setUTCDate(date.getUTCDate() + step), // offset
  (start, end) => (end - start) / 864e5, // count
  (date) => date.getUTCDate() - 1 // field
);
```

[Source](https://github.com/d3/d3-time/blob/main/src/interval.js) · Constructs a new custom interval given the specified _floor_ and _offset_ functions and an optional _count_ function.

The _floor_ function takes a single date as an argument and rounds it down to the nearest interval boundary.

The _offset_ function takes a date and an integer step as arguments and advances the specified date by the specified number of boundaries; the step may be positive, negative or zero.

The optional _count_ function takes a start date and an end date, already floored to the current interval, and returns the number of boundaries between the start (exclusive) and end (inclusive). If a _count_ function is not specified, the returned interval does not expose [_interval_.count](https://d3js.org/d3-time#interval_count) or [_interval_.every](https://d3js.org/d3-time#interval_every) methods. Note: due to an internal optimization, the specified _count_ function must not invoke _interval_.count on other time intervals.

The optional _field_ function takes a date, already floored to the current interval, and returns the field value of the specified date, corresponding to the number of boundaries between this date (exclusive) and the latest previous parent boundary. For example, for the [d3.timeDay](https://d3js.org/d3-time#timeDay) interval, this returns the number of days since the start of the month. If a _field_ function is not specified, it defaults to counting the number of interval boundaries since the UNIX epoch of January 1, 1970 UTC. The _field_ function defines the behavior of [_interval_.every](https://d3js.org/d3-time#interval_every).

## timeMillisecond [​](https://d3js.org/d3-time\#timeMillisecond)

[Source](https://github.com/d3/d3-time/blob/main/src/millisecond.js) · Milliseconds in local time; the shortest available time unit.

## timeSecond [​](https://d3js.org/d3-time\#timeSecond)

[Source](https://github.com/d3/d3-time/blob/main/src/second.js) · Seconds in local time (e.g., 01:23:45.0000 AM); 1,000 milliseconds.

## timeMinute [​](https://d3js.org/d3-time\#timeMinute)

[Source](https://github.com/d3/d3-time/blob/main/src/minute.js) · Minutes in local time (e.g., 01:02:00 AM); 60 seconds. Note that ECMAScript [ignores leap seconds](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.1).

## timeHour [​](https://d3js.org/d3-time\#timeHour)

[Source](https://github.com/d3/d3-time/blob/main/src/hour.js) · Hours in local time (e.g., 01:00 AM); 60 minutes. Note that advancing time by one hour in local time can return the same hour or skip an hour due to daylight saving.

## timeDay [​](https://d3js.org/d3-time\#timeDay)

[Source](https://github.com/d3/d3-time/blob/main/src/day.js) · Days in local time (e.g., February 7, 2012 at 12:00 AM); typically 24 hours. Days in local time may range from 23 to 25 hours due to daylight saving. d3.unixDay is like [d3.utcDay](https://d3js.org/d3-time#timeDay), except it counts days since the UNIX epoch (January 1, 1970) such that _interval_.every returns uniformly-spaced dates rather than varying based on day-of-month.

## timeWeek [​](https://d3js.org/d3-time\#timeWeek)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Alias for [d3.timeSunday](https://d3js.org/d3-time#timeSunday); 7 days and typically 168 hours. Weeks in local time may range from 167 to 169 hours due to daylight saving.

## timeSunday [​](https://d3js.org/d3-time\#timeSunday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Sunday-based weeks in local time (e.g., February 5, 2012 at 12:00 AM).

## timeMonday [​](https://d3js.org/d3-time\#timeMonday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Monday-based weeks in local time (e.g., February 6, 2012 at 12:00 AM).

## timeTuesday [​](https://d3js.org/d3-time\#timeTuesday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Tuesday-based weeks in local time (e.g., February 7, 2012 at 12:00 AM).

## timeWednesday [​](https://d3js.org/d3-time\#timeWednesday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Wednesday-based weeks in local time (e.g., February 8, 2012 at 12:00 AM).

## timeThursday [​](https://d3js.org/d3-time\#timeThursday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Thursday-based weeks in local time (e.g., February 9, 2012 at 12:00 AM).

## timeFriday [​](https://d3js.org/d3-time\#timeFriday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Friday-based weeks in local time (e.g., February 10, 2012 at 12:00 AM).

## timeSaturday [​](https://d3js.org/d3-time\#timeSaturday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Saturday-based weeks in local time (e.g., February 11, 2012 at 12:00 AM).

## timeMonth [​](https://d3js.org/d3-time\#timeMonth)

[Source](https://github.com/d3/d3-time/blob/main/src/month.js) · Months in local time (e.g., February 1, 2012 at 12:00 AM); ranges from 28 to 31 days.

## timeYear [​](https://d3js.org/d3-time\#timeYear)

[Source](https://github.com/d3/d3-time/blob/main/src/year.js) · Years in local time (e.g., January 1, 2012 at 12:00 AM); ranges from 365 to 366 days.

## utcMillisecond [​](https://d3js.org/d3-time\#utcMillisecond)

[Source](https://github.com/d3/d3-time/blob/main/src/millisecond.js) · Milliseconds in UTC time; the shortest available time unit.

## utcSecond [​](https://d3js.org/d3-time\#utcSecond)

[Source](https://github.com/d3/d3-time/blob/main/src/second.js) · Seconds in UTC time (e.g., 01:23:45.0000 AM); 1,000 milliseconds.

## utcMinute [​](https://d3js.org/d3-time\#utcMinute)

[Source](https://github.com/d3/d3-time/blob/main/src/minute.js) · Minutes in UTC time (e.g., 01:02:00 AM); 60 seconds. Note that ECMAScript [ignores leap seconds](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.1).

## utcHour [​](https://d3js.org/d3-time\#utcHour)

[Source](https://github.com/d3/d3-time/blob/main/src/hour.js) · Hours in UTC time (e.g., 01:00 AM); 60 minutes.

## utcDay [​](https://d3js.org/d3-time\#utcDay)

[Source](https://github.com/d3/d3-time/blob/main/src/day.js) · Days in UTC time (e.g., February 7, 2012 at 12:00 AM); 24 hours.

## utcWeek [​](https://d3js.org/d3-time\#utcWeek)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Alias for [d3.timeSunday](https://d3js.org/d3-time#timeSunday); 7 days and 168 hours.

## utcSunday [​](https://d3js.org/d3-time\#utcSunday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Sunday-based weeks in UTC time (e.g., February 5, 2012 at 12:00 AM).

## utcMonday [​](https://d3js.org/d3-time\#utcMonday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Monday-based weeks in UTC time (e.g., February 6, 2012 at 12:00 AM).

## utcTuesday [​](https://d3js.org/d3-time\#utcTuesday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Tuesday-based weeks in UTC time (e.g., February 7, 2012 at 12:00 AM).

## utcWednesday [​](https://d3js.org/d3-time\#utcWednesday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Wednesday-based weeks in UTC time (e.g., February 8, 2012 at 12:00 AM).

## utcThursday [​](https://d3js.org/d3-time\#utcThursday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Thursday-based weeks in UTC time (e.g., February 9, 2012 at 12:00 AM).

## utcFriday [​](https://d3js.org/d3-time\#utcFriday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Friday-based weeks in UTC time (e.g., February 10, 2012 at 12:00 AM).

## utcSaturday [​](https://d3js.org/d3-time\#utcSaturday)

[Source](https://github.com/d3/d3-time/blob/main/src/week.js) · Saturday-based weeks in UTC time (e.g., February 11, 2012 at 12:00 AM).

## utcMonth [​](https://d3js.org/d3-time\#utcMonth)

[Source](https://github.com/d3/d3-time/blob/main/src/month.js) · Months in UTC time (e.g., February 1, 2012 at 12:00 AM); ranges from 28 to 31 days.

## utcYear [​](https://d3js.org/d3-time\#utcYear)

[Source](https://github.com/d3/d3-time/blob/main/src/year.js) · Years in UTC time (e.g., January 1, 2012 at 12:00 AM); ranges from 365 to 366 days.

## unixDay [​](https://d3js.org/d3-time\#unixDay)

Like [d3.utcDay](https://d3js.org/d3-time#utcDay), except it counts days since the UNIX epoch (January 1, 1970) such that [_interval_.every](https://d3js.org/d3-time#interval_every) returns uniformly-spaced dates rather than varying based on day-of-month.

## timeMilliseconds( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeMilliseconds)

Alias for [d3.timeMillisecond](https://d3js.org/d3-time#timeMillisecond). [range](https://d3js.org/d3-time#interval_range).

## timeSeconds( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeSeconds)

Alias for [d3.timeSecond](https://d3js.org/d3-time#timeSecond). [range](https://d3js.org/d3-time#interval_range).

## timeMinutes( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeMinutes)

Alias for [d3.timeMinute](https://d3js.org/d3-time#timeMinute). [range](https://d3js.org/d3-time#interval_range).

## timeHours( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeHours)

Alias for [d3.timeHour](https://d3js.org/d3-time#timeHour). [range](https://d3js.org/d3-time#interval_range).

## timeDays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeDays)

Alias for [d3.timeDay](https://d3js.org/d3-time#timeDay). [range](https://d3js.org/d3-time#interval_range).

## timeWeeks( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeWeeks)

Alias for [d3.timeWeek](https://d3js.org/d3-time#timeWeek). [range](https://d3js.org/d3-time#interval_range).

## timeSundays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeSundays)

Alias for [d3.timeSunday](https://d3js.org/d3-time#timeSunday). [range](https://d3js.org/d3-time#interval_range).

## timeMondays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeMondays)

Alias for [d3.timeMonday](https://d3js.org/d3-time#timeMonday). [range](https://d3js.org/d3-time#interval_range).

## timeTuesdays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeTuesdays)

Alias for [d3.timeTuesday](https://d3js.org/d3-time#timeTuesday). [range](https://d3js.org/d3-time#interval_range).

## timeWednesdays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeWednesdays)

Alias for [d3.timeWednesday](https://d3js.org/d3-time#timeWednesday). [range](https://d3js.org/d3-time#interval_range).

## timeThursdays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeThursdays)

Alias for [d3.timeThursday](https://d3js.org/d3-time#timeThursday). [range](https://d3js.org/d3-time#interval_range).

## timeFridays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeFridays)

Alias for [d3.timeFriday](https://d3js.org/d3-time#timeFriday). [range](https://d3js.org/d3-time#interval_range).

## timeSaturdays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeSaturdays)

Alias for [d3.timeSaturday](https://d3js.org/d3-time#timeSaturday). [range](https://d3js.org/d3-time#interval_range).

## timeMonths( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeMonths)

Alias for [d3.timeMonth](https://d3js.org/d3-time#timeMonth). [range](https://d3js.org/d3-time#interval_range).

## timeYears( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#timeYears)

Alias for [d3.timeYear](https://d3js.org/d3-time#timeYear). [range](https://d3js.org/d3-time#interval_range).

## utcMilliseconds( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcMilliseconds)

Alias for [d3.utcMillisecond](https://d3js.org/d3-time#utcMillisecond). [range](https://d3js.org/d3-time#interval_range).

## utcSeconds( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcSeconds)

Alias for [d3.utcSecond](https://d3js.org/d3-time#utcSecond). [range](https://d3js.org/d3-time#interval_range).

## utcMinutes( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcMinutes)

Alias for [d3.utcMinute](https://d3js.org/d3-time#utcMinute). [range](https://d3js.org/d3-time#interval_range).

## utcHours( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcHours)

Alias for [d3.utcHour](https://d3js.org/d3-time#utcHour). [range](https://d3js.org/d3-time#interval_range).

## utcDays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcDays)

Alias for [d3.utcDay](https://d3js.org/d3-time#utcDay). [range](https://d3js.org/d3-time#interval_range).

## utcWeeks( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcWeeks)

Alias for [d3.utcWeek](https://d3js.org/d3-time#utcWeek). [range](https://d3js.org/d3-time#interval_range).

## utcSundays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcSundays)

Alias for [d3.utcSunday](https://d3js.org/d3-time#utcSunday). [range](https://d3js.org/d3-time#interval_range).

## utcMondays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcMondays)

Alias for [d3.utcMonday](https://d3js.org/d3-time#utcMonday). [range](https://d3js.org/d3-time#interval_range).

## utcTuesdays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcTuesdays)

Alias for [d3.utcTuesday](https://d3js.org/d3-time#utcTuesday). [range](https://d3js.org/d3-time#interval_range).

## utcWednesdays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcWednesdays)

Alias for [d3.utcWednesday](https://d3js.org/d3-time#utcWednesday). [range](https://d3js.org/d3-time#interval_range).

## utcThursdays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcThursdays)

Alias for [d3.utcThursday](https://d3js.org/d3-time#utcThursday). [range](https://d3js.org/d3-time#interval_range).

## utcFridays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcFridays)

Alias for [d3.utcFriday](https://d3js.org/d3-time#utcFriday). [range](https://d3js.org/d3-time#interval_range).

## utcSaturdays( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcSaturdays)

Alias for [d3.utcSaturday](https://d3js.org/d3-time#utcSaturday). [range](https://d3js.org/d3-time#interval_range).

## utcMonths( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcMonths)

Alias for [d3.utcMonth](https://d3js.org/d3-time#utcMonth). [range](https://d3js.org/d3-time#interval_range).

## utcYears( _start_, _stop_, _step_) [​](https://d3js.org/d3-time\#utcYears)

Alias for [d3.utcYear](https://d3js.org/d3-time#utcYear). [range](https://d3js.org/d3-time#interval_range).

## timeTicks( _start_, _stop_, _count_) [​](https://d3js.org/d3-time\#timeTicks)

[Source](https://github.com/d3/d3-time/blob/main/src/ticks.js) · Equivalent to [d3.utcTicks](https://d3js.org/d3-time#utcTicks), but in local time.

## timeTickInterval( _start_, _stop_, _count_) [​](https://d3js.org/d3-time\#timeTickInterval)

[Source](https://github.com/d3/d3-time/blob/main/src/ticks.js) · Returns the time interval that would be used by [d3.timeTicks](https://d3js.org/d3-time#timeTicks) given the same arguments.

## utcTicks( _start_, _stop_, _count_) [​](https://d3js.org/d3-time\#utcTicks)

[Source](https://github.com/d3/d3-time/blob/main/src/ticks.js) · Returns an array of approximately _count_ dates at regular intervals between _start_ and _stop_ (inclusive). If _stop_ is before _start_, dates are returned in reverse chronological order; otherwise dates are returned in chronological order. The following UTC time intervals are considered:

- 1 second
- 5 seconds
- 15 seconds
- 30 seconds
- 1 minute
- 5 minutes
- 15 minutes
- 30 minutes
- 1 hour
- 3 hours
- 6 hours
- 12 hours
- 1 day
- 2 days
- 1 week
- 1 month
- 3 months
- 1 year

Multiples of milliseconds (for small ranges) and years (for large ranges) are also considered, following the rules of [d3.ticks](https://d3js.org/d3-array/ticks#ticks). The interval producing the number of dates that is closest to _count_ is used. For example:

js

```
const start = new Date("1970-03-01");
const stop = new Date("1996-03-19");
const count = 4;
const ticks = d3.utcTicks(start, stop, count); // [1975-01-01, 1980-01-01, 1985-01-01, 1990-01-01, 1995-01-01]
```

If _count_ is a time interval, this function behaves similarly to [_interval_.range](https://d3js.org/d3-time#interval_range) except that both _start_ and _stop_ are inclusive and it may return dates in reverse chronological order if _stop_ is before _start_.

## utcTickInterval( _start_, _stop_, _count_) [​](https://d3js.org/d3-time\#utcTickInterval)

[Source](https://github.com/d3/d3-time/blob/main/src/ticks.js) · Returns the time interval that would be used by [d3.utcTicks](https://d3js.org/d3-time#utcTicks) given the same arguments. If there is no associated interval, such as when _start_ or _stop_ is invalid, returns null.

js

```
const start = new Date("1970-03-01");
const stop = new Date("1996-03-19");
const count = 4;
const interval = d3.utcTickInterval(start, stop, count); // d3.utcYear.every(5)
```

## Diverging Color Schemes
[Skip to content](https://d3js.org/d3-scale-chromatic/diverging#VPContent)

On this page

# Diverging schemes [​](https://d3js.org/d3-scale-chromatic/diverging\#diverging-schemes)

Diverging color schemes are available as continuous interpolators (often used with [d3.scaleSequential](https://d3js.org/d3-scale/sequential)) and as discrete schemes (often used with [d3.scaleOrdinal](https://d3js.org/d3-scale/ordinal)).

Each discrete scheme, such as [d3.schemeBrBG](https://d3js.org/d3-scale-chromatic/diverging#schemeBrBG), is represented as an array of arrays of hexadecimal color strings. The _k_ th element of this array contains the color scheme of size _k_; for example, `d3.schemeBrBG[9]` contains an array of nine strings representing the nine colors of the brown-blue-green diverging color scheme. Diverging color schemes support a size _k_ ranging from 3 to 11.

To create a diverging continuous color scale using the [PiYG](https://d3js.org/d3-scale-chromatic/diverging#interpolatePiYG) color scheme:

js

```
const color = d3.scaleSequential(d3.interpolatePiYG);
```

To create a diverging discrete nine-color scale using the [PiYG](https://d3js.org/d3-scale-chromatic/diverging#schemePiYG) color scheme:

js

```
const color = d3.scaleOrdinal(d3.schemePiYG[9]);
```

## interpolateBrBG(t) [​](https://d3js.org/d3-scale-chromatic/diverging\#interpolateBrBG)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/BrBG.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “BrBG” diverging color scheme represented as an RGB string.

## interpolatePRGn(t) [​](https://d3js.org/d3-scale-chromatic/diverging\#interpolatePRGn)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/PRGn.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “PRGn” diverging color scheme represented as an RGB string.

## interpolatePiYG(t) [​](https://d3js.org/d3-scale-chromatic/diverging\#interpolatePiYG)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/PiYG.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “PiYG” diverging color scheme represented as an RGB string.

## interpolatePuOr(t) [​](https://d3js.org/d3-scale-chromatic/diverging\#interpolatePuOr)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/PuOr.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “PuOr” diverging color scheme represented as an RGB string.

## interpolateRdBu(t) [​](https://d3js.org/d3-scale-chromatic/diverging\#interpolateRdBu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/RdBu.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “RdBu” diverging color scheme represented as an RGB string.

## interpolateRdGy(t) [​](https://d3js.org/d3-scale-chromatic/diverging\#interpolateRdGy)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/RdGy.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “RdGy” diverging color scheme represented as an RGB string.

## interpolateRdYlBu(t) [​](https://d3js.org/d3-scale-chromatic/diverging\#interpolateRdYlBu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/RdYlBu.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “RdYlBu” diverging color scheme represented as an RGB string.

## interpolateRdYlGn(t) [​](https://d3js.org/d3-scale-chromatic/diverging\#interpolateRdYlGn)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/RdYlGn.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “RdYlGn” diverging color scheme represented as an RGB string.

## interpolateSpectral(t) [​](https://d3js.org/d3-scale-chromatic/diverging\#interpolateSpectral)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/Spectral.js) · Given a number _t_ in the range \[0,1\], returns the corresponding color from the “Spectral” diverging color scheme represented as an RGB string.

## schemeBrBG\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/diverging\#schemeBrBG)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/BrBG.js) · The “BrBG” discrete diverging color scheme of size _k_ in 3–11.

## schemePRGn\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/diverging\#schemePRGn)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/PRGn.js) · The “PRGn” discrete diverging color scheme of size _k_ in 3–11.

## schemePiYG\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/diverging\#schemePiYG)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/PiYG.js) · The “PiYG” discrete diverging color scheme of size _k_ in 3–11.

## schemePuOr\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/diverging\#schemePuOr)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/PuOr.js) · The “PuOr” discrete diverging color scheme of size _k_ in 3–11.

## schemeRdBu\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/diverging\#schemeRdBu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/RdBu.js) · The “RdBu” discrete diverging color scheme of size _k_ in 3–11.

## schemeRdGy\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/diverging\#schemeRdGy)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/RdGy.js) · The “RdGy” discrete diverging color scheme of size _k_ in 3–11.

## schemeRdYlBu\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/diverging\#schemeRdYlBu)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/RdYlBu.js) · The “RdYlBu” discrete diverging color scheme of size _k_ in 3–11.

## schemeRdYlGn\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/diverging\#schemeRdYlGn)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/RdYlGn.js) · The “RdYlGn” discrete diverging color scheme of size _k_ in 3–11.

## schemeSpectral\[ _k_\] [​](https://d3js.org/d3-scale-chromatic/diverging\#schemeSpectral)

[Source](https://github.com/d3/d3-scale-chromatic/blob/main/src/diverging/Spectral.js) · The “Spectral” discrete diverging color scheme of size _k_ in 3–11.

## D3 Color Schemes
[Skip to content](https://d3js.org/d3-scale-chromatic#VPContent)

Return to top

# d3-scale-chromatic [​](https://d3js.org/d3-scale-chromatic\#d3-scale-chromatic)

This module provides sequential, diverging and categorical color schemes designed to work with [d3-scale](https://d3js.org/d3-scale)’s [d3.scaleOrdinal](https://d3js.org/d3-scale/ordinal) and [d3.scaleSequential](https://d3js.org/d3-scale/sequential). Most of these schemes are derived from Cynthia A. Brewer’s [ColorBrewer](http://colorbrewer2.org/). Since ColorBrewer publishes only discrete color schemes, the sequential and diverging scales are interpolated using [uniform B-splines](https://observablehq.com/@d3/colorbrewer-splines).

See one of:

- [Categorical schemes](https://d3js.org/d3-scale-chromatic/categorical)
- [Cyclical schemes](https://d3js.org/d3-scale-chromatic/cyclical)
- [Diverging schemes](https://d3js.org/d3-scale-chromatic/diverging)
- [Sequential schemes](https://d3js.org/d3-scale-chromatic/sequential)

## Transition Timing
[Skip to content](https://d3js.org/d3-transition/timing#VPContent)

On this page

# Timing [​](https://d3js.org/d3-transition/timing\#timing)

The [easing](https://d3js.org/d3-transition/timing#transition_ease), [delay](https://d3js.org/d3-transition/timing#transition_delay) and [duration](https://d3js.org/d3-transition/timing#transition_duration) of a transition is configurable. For example, a per-element delay can be used to [stagger the reordering](https://observablehq.com/@d3/sortable-bar-chart) of elements, improving perception. See [Animated Transitions in Statistical Data Graphics](http://vis.berkeley.edu/papers/animated_transitions/) for recommendations.

## _transition_.delay( _value_) [​](https://d3js.org/d3-transition/timing\#transition_delay)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/delay.js) · For each selected element, sets the transition delay to the specified _value_ in milliseconds.

js

```
transition.delay(250);
```

The _value_ may be specified either as a constant or a function. If a function, it is immediately evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The function’s return value is then used to set each element’s transition delay. If a delay is not specified, it defaults to zero.

If a _value_ is not specified, returns the current value of the delay for the first (non-null) element in the transition. This is generally useful only if you know that the transition contains exactly one element.

js

```
transition.delay() // 250
```

Setting the delay to a multiple of the index `i` is a convenient way to stagger transitions across a set of elements. For example:

js

```
transition.delay((d, i) => i * 10);
```

Of course, you can also compute the delay as a function of the data, or [sort the selection](https://d3js.org/d3-selection/modifying#selection_sort) before computed an index-based delay.

## _transition_.duration( _value_) [​](https://d3js.org/d3-transition/timing\#transition_duration)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/duration.js) · For each selected element, sets the transition duration to the specified _value_ in milliseconds.

js

```
transition.duration(750);
```

The _value_ may be specified either as a constant or a function. If a function, it is immediately evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. The function’s return value is then used to set each element’s transition duration. If a duration is not specified, it defaults to 250ms.

If a _value_ is not specified, returns the current value of the duration for the first (non-null) element in the transition. This is generally useful only if you know that the transition contains exactly one element.

js

```
transition.duration() // 750
```

## _transition_.ease( _value_) [​](https://d3js.org/d3-transition/timing\#transition_ease)

[Source](https://github.com/d3/d3-transition/blob/main/src/transition/ease.js) · Specifies the transition [easing function](https://d3js.org/d3-ease) for all selected elements.

js

```
transition.ease(d3.easeCubic);
```

The _value_ must be specified as a function. The easing function is invoked for each frame of the animation, being passed the normalized time _t_ in the range \[0, 1\]; it must then return the eased time _tʹ_ which is typically also in the range \[0, 1\]. A good easing function should return 0 if _t_ = 0 and 1 if _t_ = 1\. If an easing function is not specified, it defaults to [easeCubic](https://d3js.org/d3-ease#easeCubic).

If a _value_ is not specified, returns the current easing function for the first (non-null) element in the transition. This is generally useful only if you know that the transition contains exactly one element.

js

```
transition.ease() // d3.easeCubic
```

## _transition_.easeVarying( _factory_) [​](https://d3js.org/d3-transition/timing\#transition_easeVarying)

[Examples](https://observablehq.com/@d3/transition-easevarying) · [Source](https://github.com/d3/d3-transition/blob/main/src/transition/easeVarying.js) · Specifies a factory for the transition [easing function](https://d3js.org/d3-ease).

js

```
transition.easeVarying((d) => d3.easePolyIn.exponent(d.exponent));
```

The _factory_ must be a function. It is invoked for each node of the selection, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element. It must return an easing function.

## D3.js Radial Lines
[Skip to content](https://d3js.org/d3-shape/radial-line#VPContent)

On this page

# Radial lines [​](https://d3js.org/d3-shape/radial-line\#radial-lines)

[Examples](https://observablehq.com/@d3/d3-lineradial) · A radial line generator is like the Cartesian [line generator](https://d3js.org/d3-shape/line) except the [x](https://d3js.org/d3-shape/line#line_x) and [y](https://d3js.org/d3-shape/line#line_y) accessors are replaced with [angle](https://d3js.org/d3-shape/radial-line#lineRadial_angle) and [radius](https://d3js.org/d3-shape/radial-line#lineRadial_radius) accessors. Radial lines are positioned relative to the origin; use a [transform](http://www.w3.org/TR/SVG/coords.html#TransformAttribute) to change the origin.

## lineRadial() [​](https://d3js.org/d3-shape/radial-line\#lineRadial)

[Source](https://github.com/d3/d3-shape/blob/main/src/lineRadial.js) · Constructs a new radial line generator with the default settings.

js

```
const line = d3.lineRadial();
```

## _lineRadial_( _data_) [​](https://d3js.org/d3-shape/radial-line\#_lineRadial)

[Source](https://github.com/d3/d3-shape/blob/main/src/lineRadial.js) · Equivalent to [_line_](https://d3js.org/d3-shape/line#_line).

js

```
svg.append("path").attr("d", line(data)).attr("stroke", "currentColor");
```

## _lineRadial_.angle( _angle_) [​](https://d3js.org/d3-shape/radial-line\#lineRadial_angle)

[Source](https://github.com/d3/d3-shape/blob/main/src/lineRadial.js) · Equivalent to [_line_.x](https://d3js.org/d3-shape/line#line_x), except the accessor returns the angle in radians, with 0 at - _y_ (12 o’clock).

js

```
const line = d3.lineRadial().angle((d) => a(d.Date));
```

## _lineRadial_.radius( _radius_) [​](https://d3js.org/d3-shape/radial-line\#lineRadial_radius)

[Source](https://github.com/d3/d3-shape/blob/main/src/lineRadial.js) · Equivalent to [_line_.y](https://d3js.org/d3-shape/line#line_y), except the accessor returns the radius: the distance from the origin.

js

```
const line = d3.lineRadial().radius((d) => r(d.temperature));
```

## _lineRadial_.defined( _defined_) [​](https://d3js.org/d3-shape/radial-line\#lineRadial_defined)

[Source](https://github.com/d3/d3-shape/blob/main/src/lineRadial.js) · Equivalent to [_line_.defined](https://d3js.org/d3-shape/line#line_defined).

js

```
const line = d3.lineRadial().defined((d) => !isNaN(d.temperature));
```

## _lineRadial_.curve( _curve_) [​](https://d3js.org/d3-shape/radial-line\#lineRadial_curve)

[Source](https://github.com/d3/d3-shape/blob/main/src/lineRadial.js) · Equivalent to [_line_.curve](https://d3js.org/d3-shape/line#line_curve). Note that [curveMonotoneX](https://d3js.org/d3-shape/curve#curveMonotoneX) or [curveMonotoneY](https://d3js.org/d3-shape/curve#curveMonotoneY) are not recommended for radial lines because they assume that the data is monotonic in _x_ or _y_, which is typically untrue of radial lines.

js

```
const line = d3.lineRadial().curve(d3.curveBasis);
```

## _lineRadial_.context( _context_) [​](https://d3js.org/d3-shape/radial-line\#lineRadial_context)

[Source](https://github.com/d3/d3-shape/blob/main/src/lineRadial.js) · Equivalent to [_line_.context](https://d3js.org/d3-shape/line#line_context).

js

```
const context = canvas.getContext("2d");
const line = d3.lineRadial().context(context);
```

## D3.js Element Selection
[Skip to content](https://d3js.org/d3-selection/selecting#VPContent)

On this page

# Selecting elements [​](https://d3js.org/d3-selection/selecting\#selecting-elements)

A _selection_ is a set of elements from the DOM. Typically these elements are identified by [selectors](http://www.w3.org/TR/selectors-api/) such as `.fancy` for elements with the class _fancy_, or `div` to select DIV elements.

Selection methods come in two forms, **select** and **selectAll**: the former selects only the first matching element, while the latter selects all matching elements in document order. The top-level selection methods, [d3.select](https://d3js.org/d3-selection/selecting#select) and [d3.selectAll](https://d3js.org/d3-selection/selecting#selectAll), query the entire document; the subselection methods, [_selection_.select](https://d3js.org/d3-selection/selecting#selection_select) and [_selection_.selectAll](https://d3js.org/d3-selection/selecting#selection_selectAll), restrict selection to descendants of the selected elements. There is also [_selection_.selectChild](https://d3js.org/d3-selection/selecting#selection_selectChild) and [_selection_.selectChildren](https://d3js.org/d3-selection/selecting#selection_selectChildren) for direct children.

By convention, selection methods that return the current selection such as [_selection_.attr](https://d3js.org/d3-selection/modifying#selection_attr) use four spaces of indent, while methods that return a new selection use only two. This helps reveal changes of context by making them stick out of the chain:

js

```
d3.select("body")
  .append("svg")
    .attr("width", 960)
    .attr("height", 500)
  .append("g")
    .attr("transform", "translate(20,20)")
  .append("rect")
    .attr("width", 920)
    .attr("height", 460);
```

## selection() [​](https://d3js.org/d3-selection/selecting\#selection)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/index.js) · [Selects](https://d3js.org/d3-selection/selecting#select) the root element, `document.documentElement`.

js

```
const root = d3.selection();
```

This function can also be used to test for selections ( `instanceof d3.selection`) or to extend the selection prototype. For example, to add a method to check checkboxes:

js

```
d3.selection.prototype.checked = function(value) {
  return arguments.length < 1
      ? this.property("checked")
      : this.property("checked", !!value);
};
```

And then to use:

js

```
d3.selectAll("input[type=checkbox]").checked(true);
```

## select( _selector_) [​](https://d3js.org/d3-selection/selecting\#select)

[Source](https://github.com/d3/d3-selection/blob/main/src/select.js) · Selects the first element that matches the specified _selector_ string.

js

```
const svg = d3.select("#chart");
```

If no elements match the _selector_, returns an empty selection. If multiple elements match the _selector_, only the first matching element (in document order) will be selected. For example, to select the first anchor element:

js

```
const anchor = d3.select("a");
```

If the _selector_ is not a string, instead selects the specified node; this is useful if you already have a reference to a node, such as `document.body`.

js

```
d3.select(document.body).style("background", "red");
```

Or, to make a clicked paragraph red:

js

```
d3.selectAll("p").on("click", (event) => d3.select(event.currentTarget).style("color", "red"));
```

## selectAll( _selector_) [​](https://d3js.org/d3-selection/selecting\#selectAll)

[Source](https://github.com/d3/d3-selection/blob/main/src/selectAll.js) · Selects all elements that match the specified _selector_ string.

js

```
const p = d3.selectAll("p");
```

The elements will be selected in document order (top-to-bottom). If no elements in the document match the _selector_, or if the _selector_ is null or undefined, returns an empty selection.

If the _selector_ is not a string, instead selects the specified array of nodes; this is useful if you already have a reference to nodes, such as `this.childNodes` within an event listener or a global such as `document.links`. The nodes may instead be an iterable, or a pseudo-array such as a NodeList. For example, to color all links red:

js

```
d3.selectAll(document.links).style("color", "red");
```

## _selection_.select( _selector_) [​](https://d3js.org/d3-selection/selecting\#selection_select)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/select.js) · For each selected element, selects the first descendant element that matches the specified _selector_ string.

js

```
const b = d3.selectAll("p").select("b"); // the first <b> in every <p>
```

If no element matches the specified selector for the current element, the element at the current index will be null in the returned selection. (If the _selector_ is null, every element in the returned selection will be null, resulting in an empty selection.) If the current element has associated data, this data is propagated to the corresponding selected element. If multiple elements match the selector, only the first matching element in document order is selected.

If the _selector_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). It must return an element, or null if there is no matching element. For example, to select the previous sibling of each paragraph:

js

```
const previous = d3.selectAll("p").select(function() {
  return this.previousElementSibling;
});
```

Unlike [_selection_.selectAll](https://d3js.org/d3-selection/selecting#selection_selectAll), _selection_.select does not affect grouping: it preserves the existing group structure and indexes, and propagates data (if any) to selected children. Grouping plays an important role in the [data join](https://d3js.org/d3-selection/joining). See [Nested Selections](http://bost.ocks.org/mike/nest/) and [How Selections Work](http://bost.ocks.org/mike/selection/) for more on this topic.

CAUTION

_selection_.select propagates the parent’s data to the selected child.

## _selection_.selectAll(selector) [​](https://d3js.org/d3-selection/selecting\#selection_selectAll)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/selectAll.js) · For each selected element, selects the descendant elements that match the specified _selector_ string.

js

```
const b = d3.selectAll("p").selectAll("b"); // every <b> in every <p>
```

The elements in the returned selection are grouped by their corresponding parent node in this selection. If no element matches the specified selector for the current element, or if the _selector_ is null, the group at the current index will be empty. The selected elements do not inherit data from this selection; use [_selection_.data](https://d3js.org/d3-selection/joining#selection_data) to propagate data to children.

If the _selector_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). It must return an array of elements (or an iterable, or a pseudo-array such as a NodeList), or the empty array if there are no matching elements. For example, to select the previous and next siblings of each paragraph:

js

```
const sibling = d3.selectAll("p").selectAll(function() {
  return [\
    this.previousElementSibling,\
    this.nextElementSibling\
  ];
});
```

Unlike [_selection_.select](https://d3js.org/d3-selection/selecting#selection_select), _selection_.selectAll does affect grouping: each selected descendant is grouped by the parent element in the originating selection. Grouping plays an important role in the [data join](https://d3js.org/d3-selection/joining). See [Nested Selections](http://bost.ocks.org/mike/nest/) and [How Selections Work](http://bost.ocks.org/mike/selection/) for more on this topic.

## _selection_.filter( _filter_) [​](https://d3js.org/d3-selection/selecting\#selection_filter)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/filter.js) · Filters the selection, returning a new selection that contains only the elements for which the specified _filter_ is true. For example, to filter a selection of table rows to contain only even rows:

js

```
const even = d3.selectAll("tr").filter(":nth-child(even)");
```

This is approximately equivalent to using [d3.selectAll](https://d3js.org/d3-selection/selecting#selectAll) directly, although the indexes may be different:

js

```
const even = d3.selectAll("tr:nth-child(even)");
```

The _filter_ may be specified either as a selector string or a function. If the _filter_ is a function, it is evaluated for each selected element, in order, being passed the current datum ( _d_), the current index ( _i_), and the current group ( _nodes_), with _this_ as the current DOM element ( _nodes_\[ _i_\]). Using a function:

js

```
const even = d3.selectAll("tr").filter((d, i) => i & 1);
```

Or using [_selection_.select](https://d3js.org/d3-selection/selecting#selection_select) (and avoiding an arrow function, since _this_ is needed to refer to the current element):

js

```
const even = d3.selectAll("tr").select(function(d, i) { return i & 1 ? this : null; });
```

Note that the `:nth-child` pseudo-class is a one-based index rather than a zero-based index. Also, the above filter functions do not have precisely the same meaning as `:nth-child`; they rely on the selection index rather than the number of preceding sibling elements in the DOM.

The returned filtered selection preserves the parents of this selection, but like [_array_.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), it does not preserve indexes as some elements may be removed; use [_selection_.select](https://d3js.org/d3-selection/selecting#selection_select) to preserve the index, if needed.

## _selection_.selectChild( _selector_) [​](https://d3js.org/d3-selection/selecting\#selection_selectChild)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/selectChild.js) · Returns a new selection with the (first) child of each element of the current selection matching the _selector_.

js

```
d3.selectAll("p").selectChild("b") // the first <b> child of every <p>
```

If no _selector_ is specified, selects the first child (if any). If the _selector_ is specified as a string, selects the first child that matches (if any). If the _selector_ is a function, it is evaluated for each of the children nodes, in order, being passed the child ( _child_), the child’s index ( _i_), and the list of children ( _children_); the method selects the first child for which the selector return truthy, if any.

CAUTION

_selection_.selectChild propagates the parent’s data to the selected child.

## _selection_.selectChildren( _selector_) [​](https://d3js.org/d3-selection/selecting\#selection_selectChildren)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/selectChildren.js) · Returns a new selection with the children of each element of the current selection matching the _selector_. If no _selector_ is specified, selects all the children. If the _selector_ is specified as a string, selects the children that match (if any). If the _selector_ is a function, it is evaluated for each of the children nodes, in order, being passed the child ( _child_), the child’s index ( _i_), and the list of children ( _children_); the method selects all children for which the selector return truthy.

## _selection_.selection() [​](https://d3js.org/d3-selection/selecting\#selection_selection)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/index.js) · Returns the selection (for symmetry with [_transition_.selection](https://d3js.org/d3-transition/selecting#transition_selection)).

## matcher( _selector_) [​](https://d3js.org/d3-selection/selecting\#matcher)

[Source](https://github.com/d3/d3-selection/blob/main/src/matcher.js) · Given the specified _selector_, returns a function which returns true if `this` element [matches](https://developer.mozilla.org/en-US/docs/Web/API/Element/matches) the specified selector. This method is used internally by [_selection_.filter](https://d3js.org/d3-selection/selecting#selection_filter). For example, this:

js

```
const div = selection.filter("div");
```

Is equivalent to:

js

```
const div = selection.filter(d3.matcher("div"));
```

(Although D3 is not a compatibility layer, this implementation does support vendor-prefixed implementations due to the recent standardization of _element_.matches.)

## selector( _selector_) [​](https://d3js.org/d3-selection/selecting\#selector)

[Source](https://github.com/d3/d3-selection/blob/main/src/selector.js) · Given the specified _selector_, returns a function which returns the first descendant of `this` element that matches the specified selector. This method is used internally by [_selection_.select](https://d3js.org/d3-selection/selecting#selection_select). For example, this:

js

```
const div = selection.select("div");
```

Is equivalent to:

js

```
const div = selection.select(d3.selector("div"));
```

## selectorAll( _selector_) [​](https://d3js.org/d3-selection/selecting\#selectorAll)

[Source](https://github.com/d3/d3-selection/blob/main/src/selectAll.js) · Given the specified _selector_, returns a function which returns all descendants of `this` element that match the specified selector. This method is used internally by [_selection_.selectAll](https://d3js.org/d3-selection/selecting#selection_selectAll). For example, this:

js

```
const div = selection.selectAll("div");
```

Is equivalent to:

js

```
const div = selection.selectAll(d3.selectorAll("div"));
```

## window( _node_) [​](https://d3js.org/d3-selection/selecting\#window)

[Source](https://github.com/d3/d3-selection/blob/main/src/window.js) · Returns the owner window for the specified _node_. If _node_ is a node, returns the owner document’s default view; if _node_ is a document, returns its default view; otherwise returns the _node_.

## style( _node_, _name_) [​](https://d3js.org/d3-selection/selecting\#style)

[Source](https://github.com/d3/d3-selection/blob/main/src/selection/style.js) · Returns the value of the style property with the specified _name_ for the specified _node_. If the _node_ has an inline style with the specified _name_, its value is returned; otherwise, the [computed property value](https://developer.mozilla.org/en-US/docs/Web/CSS/computed_value) is returned. See also [_selection_.style](https://d3js.org/d3-selection/modifying#selection_style).

## D3.js Collide Force
[Skip to content](https://d3js.org/d3-force/collide#VPContent)

On this page

# Collide force [​](https://d3js.org/d3-force/collide\#collide-force)

[Fork ↗︎](https://observablehq.com/@d3/collision-detection/2)

The collide force treats nodes as circles with a given [radius](https://d3js.org/d3-force/collide#collide_radius), rather than points, and prevents nodes from overlapping. More formally, two nodes _a_ and _b_ are separated so that the distance between _a_ and _b_ is at least _radius_( _a_) \+ _radius_( _b_). To reduce jitter, this is by default a “soft” constraint with a configurable [strength](https://d3js.org/d3-force/collide#collide_strength) and [iteration count](https://d3js.org/d3-force/collide#collide_iterations).

## forceCollide( _radius_) [​](https://d3js.org/d3-force/collide\#forceCollide)

[Source](https://github.com/d3/d3-force/blob/main/src/collide.js) · Creates a new circle collide force with the specified [_radius_](https://d3js.org/d3-force/collide#collide_radius). If _radius_ is not specified, it defaults to the constant one for all nodes.

js

```
const collide = d3.forceCollide((d) => d.r);
```

## _collide_.radius( _radius_) [​](https://d3js.org/d3-force/collide\#collide_radius)

[Source](https://github.com/d3/d3-force/blob/main/src/collide.js) · If _radius_ is specified, sets the radius accessor to the specified number or function, re-evaluates the radius accessor for each node, and returns this force. If _radius_ is not specified, returns the current radius accessor, which defaults to:

js

```
function radius() {
  return 1;
}
```

The radius accessor is invoked for each [node](https://d3js.org/d3-force/simulation#simulation_nodes) in the simulation, being passed the _node_ and its zero-based _index_. The resulting number is then stored internally, such that the radius of each node is only recomputed when the force is initialized or when this method is called with a new _radius_, and not on every application of the force.

## _collide_.strength( _strength_) [​](https://d3js.org/d3-force/collide\#collide_strength)

[Source](https://github.com/d3/d3-force/blob/main/src/collide.js) · If _strength_ is specified, sets the force strength to the specified number in the range \[0,1\] and returns this force. If _strength_ is not specified, returns the current strength which defaults to 1.

Overlapping nodes are resolved through iterative relaxation. For each node, the other nodes that are anticipated to overlap at the next tick (using the anticipated positions ⟨ _x_ \+ _vx_, _y_ \+ _vy_⟩) are determined; the node’s velocity is then modified to push the node out of each overlapping node. The change in velocity is dampened by the force’s strength such that the resolution of simultaneous overlaps can be blended together to find a stable solution.

## _collide_.iterations( _iterations_) [​](https://d3js.org/d3-force/collide\#collide_iterations)

[Source](https://github.com/d3/d3-force/blob/main/src/collide.js) · If _iterations_ is specified, sets the number of iterations per application to the specified number and returns this force. If _iterations_ is not specified, returns the current iteration count which defaults to 1. Increasing the number of iterations greatly increases the rigidity of the constraint and avoids partial overlap of nodes, but also increases the runtime cost to evaluate the force.

## D3.js Gallery
[Skip to content](https://d3js.org/.https://observablehq.com/@d3/gallery?utm_source=d3js-org&utm_medium=page-nav&utm_campaign=try-observable#VPContent)

404

# PAGE NOT FOUND

> But if you don't change your direction, and if you keep looking, you may end up where you are heading.

[Take me home](https://d3js.org/)

## D3 Axis Component
[Skip to content](https://d3js.org/d3-axis#VPContent)

On this page

# d3-axis [​](https://d3js.org/d3-axis\#d3-axis)

0102030405060708090100

1231020301002003001k

ABCDEFGHIJKL

2011AprilJulyOctober2012AprilJulyOctober2013

The axis component renders human-readable reference marks for position [scales](https://d3js.org/d3-scale). It works with most scale types, including linear, log, band, and time scales as shown above.

Calling the axis component on a [selection](https://d3js.org/d3-selection) of SVG containers (usually a single G element) populates the axes. Axes are rendered at the origin. To change the position of the axis with respect to the chart, specify a [transform attribute](http://www.w3.org/TR/SVG/coords.html#TransformAttribute) on the containing element.

js

```
const gx = svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(d3.axisBottom(x));
```

If the scale has changed, call the axis component a second time to update. For smooth animations, you can call it on a [transition](https://d3js.org/d3-transition).

0102030405060708090100

js

```
gx.transition()
    .duration(750)
    .call(d3.axisBottom(x));
```

The elements created by the axis are considered part of its public API. You can apply external stylesheets or modify the generated axis elements to [customize the axis appearance](https://observablehq.com/@d3/styled-axes). An axis consists of a [path element](https://www.w3.org/TR/SVG/paths.html#PathElement) of class “domain” representing the extent of the scale’s domain, followed by transformed [g elements](https://www.w3.org/TR/SVG/struct.html#Groups) of class “tick” representing each of the scale’s ticks. Each tick has a [line element](https://www.w3.org/TR/SVG/shapes.html#LineElement) to draw the tick line, and a [text element](https://www.w3.org/TR/SVG/text.html#TextElement) for the tick label. For example, here is a typical bottom-oriented axis:

html

```
<g fill="none" font-size="10" font-family="sans-serif" text-anchor="middle">
  <path class="domain" stroke="currentColor" d="M0.5,6V0.5H880.5V6"></path>
  <g class="tick" opacity="1" transform="translate(0.5,0)">
    <line stroke="currentColor" y2="6"></line>
    <text fill="currentColor" y="9" dy="0.71em">0.0</text>
  </g>
  <g class="tick" opacity="1" transform="translate(176.5,0)">
    <line stroke="currentColor" y2="6"></line>
    <text fill="currentColor" y="9" dy="0.71em">0.2</text>
  </g>
  <g class="tick" opacity="1" transform="translate(352.5,0)">
    <line stroke="currentColor" y2="6"></line>
    <text fill="currentColor" y="9" dy="0.71em">0.4</text>
  </g>
  <g class="tick" opacity="1" transform="translate(528.5,0)">
    <line stroke="currentColor" y2="6"></line>
    <text fill="currentColor" y="9" dy="0.71em">0.6</text>
  </g>
  <g class="tick" opacity="1" transform="translate(704.5,0)">
    <line stroke="currentColor" y2="6"></line>
    <text fill="currentColor" y="9" dy="0.71em">0.8</text>
  </g>
  <g class="tick" opacity="1" transform="translate(880.5,0)">
    <line stroke="currentColor" y2="6"></line>
    <text fill="currentColor" y="9" dy="0.71em">1.0</text>
  </g>
</g>
```

The orientation of an axis is fixed; to change the orientation, remove the old axis and create a new axis.

## axisTop( _scale_) [​](https://d3js.org/d3-axis\#axisTop)

0102030405060708090100

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · Constructs a new top-oriented axis generator for the given [scale](https://d3js.org/d3-scale), with empty [tick arguments](https://d3js.org/d3-axis#axis_ticks), a [tick size](https://d3js.org/d3-axis#axis_tickSize) of 6 and [padding](https://d3js.org/d3-axis#axis_tickPadding) of 3. In this orientation, ticks are drawn above the horizontal domain path.

## axisRight( _scale_) [​](https://d3js.org/d3-axis\#axisRight)

0102030405060708090100

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · Constructs a new right-oriented axis generator for the given [scale](https://d3js.org/d3-scale), with empty [tick arguments](https://d3js.org/d3-axis#axis_ticks), a [tick size](https://d3js.org/d3-axis#axis_tickSize) of 6 and [padding](https://d3js.org/d3-axis#axis_tickPadding) of 3. In this orientation, ticks are drawn to the right of the vertical domain path.

## axisBottom( _scale_) [​](https://d3js.org/d3-axis\#axisBottom)

0102030405060708090100

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · Constructs a new bottom-oriented axis generator for the given [scale](https://d3js.org/d3-scale), with empty [tick arguments](https://d3js.org/d3-axis#axis_ticks), a [tick size](https://d3js.org/d3-axis#axis_tickSize) of 6 and [padding](https://d3js.org/d3-axis#axis_tickPadding) of 3. In this orientation, ticks are drawn below the horizontal domain path.

## axisLeft( _scale_) [​](https://d3js.org/d3-axis\#axisLeft)

0102030405060708090100

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · Constructs a new left-oriented axis generator for the given [scale](https://d3js.org/d3-scale), with empty [tick arguments](https://d3js.org/d3-axis#axis_ticks), a [tick size](https://d3js.org/d3-axis#axis_tickSize) of 6 and [padding](https://d3js.org/d3-axis#axis_tickPadding) of 3. In this orientation, ticks are drawn to the left of the vertical domain path.

## _axis_( _context_) [​](https://d3js.org/d3-axis\#_axis)

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · Render the axis to the given _context_, which may be either a [selection](https://d3js.org/d3-selection) of SVG containers (either SVG or G elements) or a corresponding [transition](https://d3js.org/d3-transition).

js

```
svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(d3.axisBottom(x));
```

## _axis_.scale( _scale_) [​](https://d3js.org/d3-axis\#axis_scale)

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · If _scale_ is specified, sets the [scale](https://d3js.org/d3-scale) and returns the axis. If _scale_ is not specified, returns the current scale.

js

```
const xAxis = d3.axisBottom().scale(x);
```

## _axis_.ticks(... _arguments_) [​](https://d3js.org/d3-axis\#axis_ticks)

Sets the _arguments_ that will be passed to [_scale_.ticks](https://d3js.org/d3-scale/linear#linear_ticks) and [_scale_.tickFormat](https://d3js.org/d3-scale/linear#linear_tickFormat) when the axis is [rendered](https://d3js.org/d3-axis#_axis), and returns the axis generator.

The meaning of the _arguments_ depends on the [axis’ scale](https://d3js.org/d3-axis#axis_scale) type: most commonly, the arguments are a suggested _count_ for the number of ticks (or a [time _interval_](https://d3js.org/d3-time) for time scales), and an optional [format _specifier_](https://d3js.org/d3-format) to customize how the tick values are formatted. For example, to generate twenty ticks with SI-prefix formatting on a linear scale, say:

js

```
axis.ticks(20, "s");
```

To generate ticks every fifteen minutes with a time scale, say:

js

```
axis.ticks(d3.timeMinute.every(15));
```

This method is a convenience function for [_axis_.tickArguments](https://d3js.org/d3-axis#axis_tickArguments). For example, this:

js

```
axis.ticks(10);
```

Is equivalent to:

js

```
axis.tickArguments([10]);
```

This method has no effect if the scale does not implement _scale_.ticks, as with [band](https://d3js.org/d3-scale/band) and [point](https://d3js.org/d3-scale/point) scales. To set the tick values explicitly, use [_axis_.tickValues](https://d3js.org/d3-axis#axis_tickValues). To set the tick format explicitly, use [_axis_.tickFormat](https://d3js.org/d3-axis#axis_tickFormat). To generate tick values directly, use [_scale_.ticks](https://d3js.org/d3-scale/linear#linear_ticks).

## _axis_.tickArguments( _arguments_) [​](https://d3js.org/d3-axis\#axis_tickArguments)

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · If _arguments_ is specified, sets the _arguments_ that will be passed to [_scale_.ticks](https://d3js.org/d3-scale/linear#linear_ticks) and [_scale_.tickFormat](https://d3js.org/d3-scale/linear#linear_tickFormat) when the axis is [rendered](https://d3js.org/d3-axis#_axis), and returns the axis generator. See also [_axis_.ticks](https://d3js.org/d3-axis#axis_ticks), which is used more commonly.

The meaning of the _arguments_ depends on the [axis’ scale](https://d3js.org/d3-axis#axis_scale) type: most commonly, the arguments are a suggested _count_ for the number of ticks (or a [time _interval_](https://d3js.org/d3-time) for time scales), and an optional [format _specifier_](https://d3js.org/d3-format) to customize how the tick values are formatted. For example, to generate twenty ticks with SI-prefix formatting on a linear scale, say:

js

```
axis.tickArguments([20, "s"]);
```

To generate ticks every fifteen minutes with a time scale, say:

js

```
axis.tickArguments([d3.timeMinute.every(15)]);
```

If _arguments_ is not specified, returns the current tick arguments, which defaults to the empty array. If _arguments_ is specified, this method has no effect if the scale does not implement _scale_.ticks, as with [band](https://d3js.org/d3-scale/band) and [point](https://d3js.org/d3-scale/point) scales. To set the tick values explicitly, use [_axis_.tickValues](https://d3js.org/d3-axis#axis_tickValues). To set the tick format explicitly, use [_axis_.tickFormat](https://d3js.org/d3-axis#axis_tickFormat).

## _axis_.tickValues( _values_) [​](https://d3js.org/d3-axis\#axis_tickValues)

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · If a _values_ iterable is specified, the specified values are used for ticks rather than the scale’s automatic tick generator. For example, to generate ticks at specific values:

js

```
const axis = d3.axisBottom(x).tickValues([1, 2, 3, 5, 8, 13, 21]);
```

The explicit tick values take precedence over the tick arguments set by [_axis_.tickArguments](https://d3js.org/d3-axis#axis_tickArguments). However, any tick arguments will still be passed to the scale’s [tickFormat](https://d3js.org/d3-axis#axis_tickFormat) function if a tick format is not also set.

If _values_ is null, clears any previously-set explicit tick values and reverts back to the scale’s tick generator. If _values_ is not specified, returns the current tick values, which defaults to null.

## _axis_.tickFormat( _format_) [​](https://d3js.org/d3-axis\#axis_tickFormat)

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · If _format_ is specified, sets the tick format function and returns the axis. For example, to display integers with comma-grouping for thousands:

js

```
axis.tickFormat(d3.format(",.0f"));
```

More commonly, a format specifier is passed to [_axis_.ticks](https://d3js.org/d3-axis#axis_ticks), which has the advantage of setting the format precision automatically based on the tick interval:

js

```
axis.ticks(10, ",f");
```

See [d3-format](https://d3js.org/d3-format) and [d3-time-format](https://d3js.org/d3-time-format) for help creating formatters.

If _format_ is not specified, returns the current format function, which defaults to null. A null format indicates that the scale’s default formatter should be used, which is generated by calling [_scale_.tickFormat](https://d3js.org/d3-scale/linear#linear_tickFormat). In this case, the arguments specified by [_axis_.tickArguments](https://d3js.org/d3-axis#axis_tickArguments) are likewise passed to _scale_.tickFormat.

## _axis_.tickSize( _size_) [​](https://d3js.org/d3-axis\#axis_tickSize)

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · If _size_ is specified, sets the [inner](https://d3js.org/d3-axis#axis_tickSizeInner) and [outer](https://d3js.org/d3-axis#axis_tickSizeOuter) tick size to the specified value and returns the axis.

js

```
const axis = d3.axisBottom(x).tickSize(0);
```

If _size_ is not specified, returns the current inner tick size, which defaults to 6.

js

```
axis.tickSize() // 0, as specified above
```

## _axis_.tickSizeInner(size) [​](https://d3js.org/d3-axis\#axis_tickSizeInner)

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · If _size_ is specified, sets the inner tick size to the specified value and returns the axis.

js

```
const axis = d3.axisBottom(x).tickSizeInner(0);
```

If _size_ is not specified, returns the current inner tick size, which defaults to 6.

js

```
axis.tickSizeInner() // 0, as specified above
```

The inner tick size controls the length of the tick lines, offset from the native position of the axis.

## _axis_.tickSizeOuter(size) [​](https://d3js.org/d3-axis\#axis_tickSizeOuter)

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · If _size_ is specified, sets the outer tick size to the specified value and returns the axis.

js

```
const axis = d3.axisBottom(x).tickSizeOuter(0);
```

If _size_ is not specified, returns the current outer tick size, which defaults to 6.

js

```
axis.tickSizeOuter() // 0, as specified above
```

The outer tick size controls the length of the square ends of the domain path, offset from the native position of the axis. Thus, the “outer ticks” are not actually ticks but part of the domain path, and their position is determined by the associated scale’s domain extent. Thus, outer ticks may overlap with the first or last inner tick. An outer tick size of 0 suppresses the square ends of the domain path, instead producing a straight line.

## _axis_.tickPadding(padding) [​](https://d3js.org/d3-axis\#axis_tickPadding)

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · If _padding_ is specified, sets the padding to the specified value in pixels and returns the axis.

js

```
const axis = d3.axisBottom(x).tickPadding(0);
```

If _padding_ is not specified, returns the current padding which defaults to 3 pixels.

js

```
axis.tickPadding() // 0, as specified above
```

## _axis_.offset(offset) [​](https://d3js.org/d3-axis\#axis_offset)

[Source](https://github.com/d3/d3-axis/blob/main/src/axis.js) · If _offset_ is specified, sets the pixel offset to the specified value in pixels and returns the axis.

js

```
const axis = d3.axisBottom(x).offset(0);
```

If _offset_ is not specified, returns the current pixel offset.

js

```
axis.offset() // 0
```

The pixel offset defaults to 0 on devices with a [devicePixelRatio](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio) greater than 1, and 0.5 otherwise. This default pixel offset ensures crisp edges on low-resolution devices.

## D3.js Force Simulation
[Skip to content](https://d3js.org/d3-force/simulation#VPContent)

On this page

# Force simulations [​](https://d3js.org/d3-force/simulation\#force-simulations)

A force simulation implements a [velocity Verlet](https://en.wikipedia.org/wiki/Verlet_integration) numerical integrator for simulating physical forces on particles (nodes). The simulation assumes a constant unit time step Δ _t_ = 1 for each step and a constant unit mass _m_ = 1 for all particles. As a result, a force _F_ acting on a particle is equivalent to a constant acceleration _a_ over the time interval Δ _t_, and can be simulated simply by adding to the particle’s velocity, which is then added to the particle’s position.

## forceSimulation( _nodes_) [​](https://d3js.org/d3-force/simulation\#forceSimulation)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · Creates a new simulation with the specified array of [_nodes_](https://d3js.org/d3-force/simulation#simulation_nodes) and no [forces](https://d3js.org/d3-force/simulation#simulation_force). If _nodes_ is not specified, it defaults to the empty array.

WARNING

This function is impure; it mutates the passed-in _nodes_. See [_simulation_.nodes](https://d3js.org/d3-force/simulation#simulation_nodes).

js

```
const simulation = d3.forceSimulation(nodes);
```

The simulator [starts](https://d3js.org/d3-force/simulation#simulation_restart) automatically; use [_simulation_.on](https://d3js.org/d3-force/simulation#simulation_on) to listen for tick events as the simulation runs. If you wish to run the simulation manually instead, call [_simulation_.stop](https://d3js.org/d3-force/simulation#simulation_stop), and then call [_simulation_.tick](https://d3js.org/d3-force/simulation#simulation_tick) as desired.

## _simulation_.restart() [​](https://d3js.org/d3-force/simulation\#simulation_restart)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · Restarts the simulation’s internal timer and returns the simulation. In conjunction with [_simulation_.alphaTarget](https://d3js.org/d3-force/simulation#simulation_alphaTarget) or [_simulation_.alpha](https://d3js.org/d3-force/simulation#simulation_alpha), this method can be used to “reheat” the simulation during interaction, such as when dragging a node, or to resume the simulation after temporarily pausing it with [_simulation_.stop](https://d3js.org/d3-force/simulation#simulation_stop).

## _simulation_.stop() [​](https://d3js.org/d3-force/simulation\#simulation_stop)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · Stops the simulation’s internal timer, if it is running, and returns the simulation. If the timer is already stopped, this method does nothing. This method is useful for running the simulation manually; see [_simulation_.tick](https://d3js.org/d3-force/simulation#simulation_tick).

## _simulation_.tick( _iterations_) [​](https://d3js.org/d3-force/simulation\#simulation_tick)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · Manually steps the simulation by the specified number of _iterations_, and returns the simulation. If _iterations_ is not specified, it defaults to 1 (single step).

For each iteration, it increments the current [_alpha_](https://d3js.org/d3-force/simulation#simulation_alpha) by ( [_alphaTarget_](https://d3js.org/d3-force/simulation#simulation_alphaTarget) \- _alpha_) × [_alphaDecay_](https://d3js.org/d3-force/simulation#simulation_alphaDecay); then invokes each registered [force](https://d3js.org/d3-force/simulation#simulation_force), passing the new _alpha_; then decrements each [node](https://d3js.org/d3-force/simulation#simulation_nodes)’s velocity by _velocity_ × [_velocityDecay_](https://d3js.org/d3-force/simulation#simulation_velocityDecay); lastly increments each node’s position by _velocity_.

This method does not dispatch [events](https://d3js.org/d3-force/simulation#simulation_on); events are only dispatched by the internal timer when the simulation is started automatically upon [creation](https://d3js.org/d3-force/simulation#forceSimulation) or by calling [_simulation_.restart](https://d3js.org/d3-force/simulation#simulation_restart). The natural number of ticks when the simulation is started is ⌈ _log_( [_alphaMin_](https://d3js.org/d3-force/simulation#simulation_alphaMin)) / _log_(1 - [_alphaDecay_](https://d3js.org/d3-force/simulation#simulation_alphaDecay))⌉; by default, this is 300.

This method can be used in conjunction with [_simulation_.stop](https://d3js.org/d3-force/simulation#simulation_stop) to compute a [static force layout](https://observablehq.com/@d3/static-force-directed-graph). For large graphs, static layouts should be computed [in a web worker](https://observablehq.com/@d3/force-directed-web-worker) to avoid freezing the user interface.

## _simulation_.nodes( _nodes_) [​](https://d3js.org/d3-force/simulation\#simulation_nodes)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · If _nodes_ is specified, sets the simulation’s nodes to the specified array of objects, initializing their positions and velocities if necessary, and then [re-initializes](https://d3js.org/d3-force/simulation#force_initialize) any bound [forces](https://d3js.org/d3-force/simulation#simulation_force); returns the simulation. If _nodes_ is not specified, returns the simulation’s array of nodes as specified to the [constructor](https://d3js.org/d3-force/simulation#forceSimulation).

WARNING

This function is impure; it mutates the passed-in _nodes_ to assign the index _node_.index, the position _node_.x & _node_.y, and the velocity _node_.vx & _node_.vy. The position and velocity are further updated as the simulation runs by [_simulation_.tick](https://d3js.org/d3-force/simulation#simulation_tick).

Each _node_ must be an object. The following properties are assigned by the simulation:

- `index` \- the node’s zero-based index into _nodes_
- `x` \- the node’s current _x_-position
- `y` \- the node’s current _y_-position
- `vx` \- the node’s current _x_-velocity
- `vy` \- the node’s current _y_-velocity

The position ⟨ _x_, _y_⟩ and velocity ⟨ _vx_, _vy_⟩ may be subsequently modified by [forces](https://d3js.org/d3-force/simulation#custom-forces) and by the simulation. If either _vx_ or _vy_ is NaN, the velocity is initialized to ⟨0,0⟩. If either _x_ or _y_ is NaN, the position is initialized in a [phyllotaxis arrangement](https://observablehq.com/@d3/force-layout-phyllotaxis), so chosen to ensure a deterministic, uniform distribution.

To fix a node in a given position, you may specify two additional properties:

- `fx` \- the node’s fixed _x_-position
- `fy` \- the node’s fixed _y_-position

At the end of each [tick](https://d3js.org/d3-force/simulation#simulation_tick), after the application of any forces, a node with a defined _node_.fx has _node_.x reset to this value and _node_.vx set to zero; likewise, a node with a defined _node_.fy has _node_.y reset to this value and _node_.vy set to zero. To unfix a node that was previously fixed, set _node_.fx and _node_.fy to null, or delete these properties.

If the specified array of _nodes_ is modified, such as when nodes are added to or removed from the simulation, this method must be called again with the new (or changed) array to notify the simulation and bound forces of the change; the simulation does not make a defensive copy of the specified array.

## _simulation_.alpha( _alpha_) [​](https://d3js.org/d3-force/simulation\#simulation_alpha)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · _alpha_ is roughly analogous to temperature in [simulated annealing](https://en.wikipedia.org/wiki/Simulated_annealing#Overview). It decreases over time as the simulation “cools down”. When _alpha_ reaches _alphaMin_, the simulation stops; see [_simulation_.restart](https://d3js.org/d3-force/simulation#simulation_restart).

If _alpha_ is specified, sets the current alpha to the specified number in the range \[0,1\] and returns this simulation. If _alpha_ is not specified, returns the current alpha value, which defaults to 1.

## _simulation_.alphaMin( _min_) [​](https://d3js.org/d3-force/simulation\#simulation_alphaMin)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · If _min_ is specified, sets the minimum _alpha_ to the specified number in the range \[0,1\] and returns this simulation. If _min_ is not specified, returns the current minimum _alpha_ value, which defaults to 0.001. The simulation’s internal timer stops when the current [_alpha_](https://d3js.org/d3-force/simulation#simulation_alpha) is less than the minimum _alpha_. The default [alpha decay rate](https://d3js.org/d3-force/simulation#simulation_alphaDecay) of ~0.0228 corresponds to 300 iterations.

## _simulation_.alphaDecay( _decay_) [​](https://d3js.org/d3-force/simulation\#simulation_alphaDecay)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · If _decay_ is specified, sets the [_alpha_](https://d3js.org/d3-force/simulation#simulation_alpha) decay rate to the specified number in the range \[0,1\] and returns this simulation. If _decay_ is not specified, returns the current _alpha_ decay rate, which defaults to 0.0228… = 1 - _pow_(0.001, 1 / 300) where 0.001 is the default [minimum _alpha_](https://d3js.org/d3-force/simulation#simulation_alphaMin).

The alpha decay rate determines how quickly the current alpha interpolates towards the desired [target _alpha_](https://d3js.org/d3-force/simulation#simulation_alphaTarget); since the default target _alpha_ is zero, by default this controls how quickly the simulation cools. Higher decay rates cause the simulation to stabilize more quickly, but risk getting stuck in a local minimum; lower values cause the simulation to take longer to run, but typically converge on a better layout. To have the simulation run forever at the current _alpha_, set the _decay_ rate to zero; alternatively, set a [target _alpha_](https://d3js.org/d3-force/simulation#simulation_alphaTarget) greater than the [minimum _alpha_](https://d3js.org/d3-force/simulation#simulation_alphaMin).

## _simulation_.alphaTarget( _target_) [​](https://d3js.org/d3-force/simulation\#simulation_alphaTarget)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · If _target_ is specified, sets the current target [_alpha_](https://d3js.org/d3-force/simulation#simulation_alpha) to the specified number in the range \[0,1\] and returns this simulation. If _target_ is not specified, returns the current target alpha value, which defaults to 0.

## _simulation_.velocityDecay( _decay_) [​](https://d3js.org/d3-force/simulation\#simulation_velocityDecay)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · If _decay_ is specified, sets the velocity decay factor to the specified number in the range \[0,1\] and returns this simulation. If _decay_ is not specified, returns the current velocity decay factor, which defaults to 0.4. The decay factor is akin to atmospheric friction; after the application of any forces during a [tick](https://d3js.org/d3-force/simulation#simulation_tick), each node’s velocity is multiplied by 1 - _decay_. As with lowering the [alpha decay rate](https://d3js.org/d3-force/simulation#simulation_alphaDecay), less velocity decay may converge on a better solution, but risks numerical instabilities and oscillation.

## _simulation_.force( _name_, _force_) [​](https://d3js.org/d3-force/simulation\#simulation_force)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · If _force_ is specified, assigns the [force](https://d3js.org/d3-force/simulation#custom-forces) for the specified _name_ and returns this simulation. If _force_ is not specified, returns the force with the specified name, or undefined if there is no such force. (By default, new simulations have no forces.) For example, to create a new simulation to layout a graph, you might say:

js

```
const simulation = d3.forceSimulation(nodes)
    .force("charge", d3.forceManyBody())
    .force("link", d3.forceLink(links))
    .force("center", d3.forceCenter());
```

To remove the force with the given _name_, pass null as the _force_. For example, to remove the charge force:

js

```
simulation.force("charge", null);
```

## _simulation_.find( _x_, _y_, _radius_) [​](https://d3js.org/d3-force/simulation\#simulation_find)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · Returns the node closest to the position ⟨ _x_, _y_⟩ with the given search _radius_. If _radius_ is not specified, it defaults to infinity. If there is no node within the search area, returns undefined.

## _simulation_.randomSource( _source_) [​](https://d3js.org/d3-force/simulation\#simulation_randomSource)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js "Source"))

If _source_ is specified, sets the function used to generate random numbers; this should be a function that returns a number between 0 (inclusive) and 1 (exclusive). If _source_ is not specified, returns this simulation’s current random source which defaults to a fixed-seed [linear congruential generator](https://en.wikipedia.org/wiki/Linear_congruential_generator). See also [_random_.source](https://d3js.org/d3-random#random_source).

## _simulation_.on( _typenames_, _listener_) [​](https://d3js.org/d3-force/simulation\#simulation_on)

[Source](https://github.com/d3/d3-force/blob/main/src/simulation.js) · If _listener_ is specified, sets the event _listener_ for the specified _typenames_ and returns this simulation. 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 `this` context as the simulation.

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 `tick.foo` and `tick.bar`; the name allows multiple listeners to be registered for the same _type_. The _type_ must be one of the following:

- `tick` \- after each tick of the simulation’s internal timer.
- `end` \- after the simulation’s timer stops when _alpha_ < [_alphaMin_](https://d3js.org/d3-force/simulation#simulation_alphaMin).

Note that _tick_ events are not dispatched when [_simulation_.tick](https://d3js.org/d3-force/simulation#simulation_tick) is called manually; events are only dispatched by the internal timer and are intended for interactive rendering of the simulation. To affect the simulation, register [forces](https://d3js.org/d3-force/simulation#simulation_force) instead of modifying nodes’ positions or velocities inside a tick event listener.

See [_dispatch_.on](https://d3js.org/d3-dispatch#dispatch_on) for details.

## Custom forces [​](https://d3js.org/d3-force/simulation\#custom-forces)

A _force_ is a function that modifies nodes’ positions or velocities. It can simulate a physical force such as electrical charge or gravity, or it can resolve a geometric constraint such as keeping nodes within a bounding box or keeping linked nodes a fixed distance apart. For example, here is a force that moves nodes towards the origin:

js

```
function force(alpha) {
  for (let i = 0, n = nodes.length, node, k = alpha * 0.1; i < n; ++i) {
    node = nodes[i];
    node.vx -= node.x * k;
    node.vy -= node.y * k;
  }
}
```

Forces typically read the node’s current position ⟨ _x_, _y_⟩ and then mutate the node’s velocity ⟨ _vx_, _vy_⟩. Forces may also “peek ahead” to the anticipated next position of the node, ⟨ _x_ \+ _vx_, _y_ \+ _vy_⟩; this is necessary for resolving geometric constraints through [iterative relaxation](https://en.wikipedia.org/wiki/Relaxation_(iterative_method)). Forces may also modify the position directly, which is sometimes useful to avoid adding energy to the simulation, such as when recentering the simulation in the viewport.

### _force_( _alpha_) [​](https://d3js.org/d3-force/simulation\#_force)

Applies this force, optionally observing the specified _alpha_. Typically, the force is applied to the array of nodes previously passed to [_force_.initialize](https://d3js.org/d3-force/simulation#force_initialize), however, some forces may apply to a subset of nodes, or behave differently. For example, [forceLink](https://d3js.org/d3-force/link) applies to the source and target of each link.

### _force_.initialize( _nodes_) [​](https://d3js.org/d3-force/simulation\#force_initialize)

Supplies the array of _nodes_ and _random_ source to this force. This method is called when a force is bound to a simulation via [_simulation_.force](https://d3js.org/d3-force/simulation#simulation_force) and when the simulation’s nodes change via [_simulation_.nodes](https://d3js.org/d3-force/simulation#simulation_nodes). A force may perform necessary work during initialization, such as evaluating per-node parameters, to avoid repeatedly performing work during each application of the force.

## D3 Data Visualization
[Skip to content](https://d3js.org/#VPContent)

# D3

The JavaScript library for bespoke data visualization

Create custom dynamic visualizations with unparalleled flexibility

[Get started](https://d3js.org/getting-started)

[What is D3?](https://d3js.org/what-is-d3)

[Examples](https://observablehq.com/@d3/gallery?utm_source=d3js-org&utm_medium=hero&utm_campaign=try-observable)

![D3](https://d3js.org/logo.svg)

[**Selections and transitions** \\
\\
Create, update, and animate the DOM based on data without the overhead of a virtual DOM.](https://d3js.org/d3-selection)

[**Scales and axes** \\
\\
Encode abstract data into visual values such as position, size, and color. Explain position encodings with axes.](https://d3js.org/d3-scale)

[**Shapes** \\
\\
Render arcs, areas, curves, lines, links, pies, stacks, symbols… and any geometric primitive you might need to visualize data.](https://d3js.org/d3-shape)

[**Interactions** \\
\\
Facilitate exploration with reusable interactive behaviors, including panning, zooming, brushing, and dragging.](https://d3js.org/d3-brush)

[**Layouts** \\
\\
Treemaps, trees, force-directed graphs, Voronoi, contours, chords, circle-packing… a library of layout algorithms at the ready.](https://d3js.org/d3-hierarchy)

[**Geographic maps** \\
\\
More spherical projections than you can shake a stick at, with arbitrary aspects, adaptive sampling, and flexible clipping.](https://d3js.org/d3-geo)

[**… and much more!** \\
\\
CSV parsing, localized date parsing and formatting, color spaces, calendar math, statistics, and can I stop listing features now?](https://d3js.org/d3-array)

[**Powering Observable Plot** \\
\\
The D3 team also builds Observable Plot, a high-level API for quick charts built on top of D3.\\
\\
Try Observable Plot](https://observablehq.com/plot?utm_source=d3js-org&utm_medium=features&utm_campaign=try-observable)

[**Built by Observable** \\
\\
D3 is developed by Observable, the platform for collaborative data analysis.\\
\\
Visit Observable](https://observablehq.com/?utm_source=d3js-org&utm_medium=features&utm_campaign=try-observable)

# Build your best work with D3 on Observable

The only data workflow platform capable of supporting the full power of D3

Connect to your data instantlyPull live data from the cloud, files, and databases into one secure place — without installing anything, ever.

Code faster than you thought possibleGet everything you need and none of what you don’t with lightweight automatic versioning, instant sharing, and real-time multiplayer editing.

Accelerate your team’s analysisCreate a home for your team’s data analysis where you can spin up charts, maps, and data apps to explore, analyze, and iterate on together.

[Build with D3 on Observable →](https://observablehq.com/?utm_source=d3js-org&utm_medium=promo&utm_campaign=try-observable)

## Set Operations Overview
[Skip to content](https://d3js.org/d3-array/sets#VPContent)

On this page

# Set operations [​](https://d3js.org/d3-array/sets\#set-operations)

Logical set operations for any iterable.

## difference( _iterable_, ... _others_) [​](https://d3js.org/d3-array/sets\#difference)

[Source](https://github.com/d3/d3-array/blob/main/src/difference.js) · Returns a new [InternSet](https://d3js.org/d3-array/intern#InternSet) containing every value in _iterable_ that is not in any of the _others_ iterables.

js

```
d3.difference([0, 1, 2, 0], [1]) // Set {0, 2}
```

## union(... _iterables_) [​](https://d3js.org/d3-array/sets\#union)

[Source](https://github.com/d3/d3-array/blob/main/src/union.js) · Returns a new [InternSet](https://d3js.org/d3-array/intern#InternSet) containing every (distinct) value that appears in any of the given _iterables_. The order of values in the returned set is based on their first occurrence in the given _iterables_.

js

```
d3.union([0, 2, 1, 0], [1, 3]) // Set {0, 2, 1, 3}
```

## intersection(... _iterables_) [​](https://d3js.org/d3-array/sets\#intersection)

[Source](https://github.com/d3/d3-array/blob/main/src/intersection.js) · Returns a new [InternSet](https://d3js.org/d3-array/intern#InternSet) containing every (distinct) value that appears in all of the given _iterables_. The order of values in the returned set is based on their first occurrence in the given _iterables_.

js

```
d3.intersection([0, 2, 1, 0], [1, 3]) // Set {1}
```

## superset( _a_, _b_) [​](https://d3js.org/d3-array/sets\#superset)

[Source](https://github.com/d3/d3-array/blob/main/src/superset.js) · Returns true if _a_ is a superset of _b_: if every value in the given iterable _b_ is also in the given iterable _a_.

js

```
d3.superset([0, 2, 1, 3, 0], [1, 3]) // true
```

## subset( _a_, _b_) [​](https://d3js.org/d3-array/sets\#subset)

[Source](https://github.com/d3/d3-array/blob/main/src/subset.js) · Returns true if _a_ is a subset of _b_: if every value in the given iterable _a_ is also in the given iterable _b_.

js

```
d3.subset([1, 3], [0, 2, 1, 3, 0]) // true
```

## disjoint( _a_, _b_) [​](https://d3js.org/d3-array/sets\#disjoint)

[Source](https://github.com/d3/d3-array/blob/main/src/disjoint.js) · Returns true if _a_ and _b_ are disjoint: if _a_ and _b_ contain no shared value.

js

```
d3.disjoint([1, 3], [2, 4]) // true
```

## D3.js Time Scales
[Skip to content](https://d3js.org/d3-scale/time#VPContent)

On this page

# Time scales [​](https://d3js.org/d3-scale/time\#time-scales)

Time scales are a variant of [linear scales](https://d3js.org/d3-scale/linear) that have a temporal domain: domain values are coerced to [dates](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) rather than numbers, and invert likewise returns a date. Time scales implement [ticks](https://d3js.org/d3-scale/time#time_ticks) based on [calendar intervals](https://d3js.org/d3-time), taking the pain out of generating axes for temporal domains.

## scaleTime( _domain_, _range_) [​](https://d3js.org/d3-scale/time\#scaleTime)

[Examples](https://observablehq.com/@d3/d3-scaletime) · [Source](https://github.com/d3/d3-scale/blob/main/src/time.js) · Constructs a new time scale with the specified [domain](https://d3js.org/d3-scale/linear#linear_domain) and [range](https://d3js.org/d3-scale/linear#linear_range), the [default](https://d3js.org/d3-interpolate/value#interpolate) [interpolator](https://d3js.org/d3-scale/linear#linear_interpolate) and [clamping](https://d3js.org/d3-scale/linear#linear_clamp) disabled. For example, to create a position encoding:

js

```
const x = d3.scaleTime([new Date(2000, 0, 1), new Date(2000, 0, 2)], [0, 960]);
x(new Date(2000, 0, 1, 5)); // 200
x(new Date(2000, 0, 1, 16)); // 640
x.invert(200); // Sat Jan 01 2000 05:00:00 GMT-0800 (PST)
x.invert(640); // Sat Jan 01 2000 16:00:00 GMT-0800 (PST)
```

If _domain_ is not specified, it defaults to \[2000-01-01, 2000-01-02\] in local time. If _range_ is not specified, it defaults to \[0, 1\].

## scaleUtc( _domain_, _range_) [​](https://d3js.org/d3-scale/time\#scaleUtc)

[Examples](https://observablehq.com/@d3/d3-scaletime) · [Source](https://github.com/d3/d3-scale/blob/main/src/utcTime.js) · Equivalent to [scaleTime](https://d3js.org/d3-scale/time#scaleTime), but the returned time scale operates in [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) rather than local time. For example, to create a position encoding:

js

```
const x = d3.scaleUtc([new Date("2000-01-01"), new Date("2000-01-02")], [0, 960]);
x(new Date("2000-01-01T05:00Z")); // 200
x(new Date("2000-01-01T16:00Z")); // 640
x.invert(200); // 2000-01-01T05:00Z
x.invert(640); // 2000-01-01T16:00Z
```

If _domain_ is not specified, it defaults to \[2000-01-01, 2000-01-02\] in UTC time. If _range_ is not specified, it defaults to \[0, 1\].

TIP

A UTC scale should be preferred when possible as it behaves more predictably: days are always twenty-four hours and the scale does not depend on the browser’s time zone.

## _time_.ticks( _count_) [​](https://d3js.org/d3-scale/time\#time_ticks)

[Examples](https://observablehq.com/@d3/d3-scaletime) · [Source](https://github.com/d3/d3-scale/blob/main/src/time.js) · Returns representative dates from the scale’s domain.

js

```
const x = d3.scaleTime();
x.ticks(10);
// [Sat Jan 01 2000 00:00:00 GMT-0800 (PST),\
//  Sat Jan 01 2000 03:00:00 GMT-0800 (PST),\
//  Sat Jan 01 2000 06:00:00 GMT-0800 (PST),\
//  Sat Jan 01 2000 09:00:00 GMT-0800 (PST),\
//  Sat Jan 01 2000 12:00:00 GMT-0800 (PST),\
//  Sat Jan 01 2000 15:00:00 GMT-0800 (PST),\
//  Sat Jan 01 2000 18:00:00 GMT-0800 (PST),\
//  Sat Jan 01 2000 21:00:00 GMT-0800 (PST),\
//  Sun Jan 02 2000 00:00:00 GMT-0800 (PST)]
```

The returned tick values are uniformly-spaced (mostly), have sensible values (such as every day at midnight), and are guaranteed to be within the extent of the domain. Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data.

An optional _count_ may be specified to affect how many ticks are generated. If _count_ is not specified, it defaults to 10. The specified _count_ is only a hint; the scale may return more or fewer values depending on the domain.

The following time intervals are considered for automatic ticks:

- 1-, 5-, 15- and 30-second.
- 1-, 5-, 15- and 30-minute.
- 1-, 3-, 6- and 12-hour.
- 1- and 2-day.
- 1-week.
- 1- and 3-month.
- 1-year.

In lieu of a _count_, a [time _interval_](https://d3js.org/d3-time#_interval) may be explicitly specified. To prune the generated ticks for a given time _interval_, use [_interval_.every](https://d3js.org/d3-time#interval_every). For example, to generate ticks at 15-minute intervals:

js

```
const x = d3.scaleUtc().domain([new Date("2000-01-01T00:00Z"), new Date("2000-01-01T02:00Z")]);
x.ticks(d3.utcMinute.every(15));
// [2000-01-01T00:00Z,\
//  2000-01-01T00:15Z,\
//  2000-01-01T00:30Z,\
//  2000-01-01T00:45Z,\
//  2000-01-01T01:00Z,\
//  2000-01-01T01:15Z,\
//  2000-01-01T01:30Z,\
//  2000-01-01T01:45Z,\
//  2000-01-01T02:00Z]
```

Note: in some cases, such as with day ticks, specifying a _step_ can result in irregular spacing of ticks because time intervals have varying length.

## _time_.tickFormat( _count_, _specifier_) [​](https://d3js.org/d3-scale/time\#time_tickFormat)

[Examples](https://observablehq.com/@d3/scale-ticks) · [Source](https://github.com/d3/d3-scale/blob/main/src/time.js) · Returns a time format function suitable for displaying [tick](https://d3js.org/d3-scale/time#time_ticks) values.

js

```
const x = d3.scaleUtc().domain([new Date("2000-01-01T00:00Z"), new Date("2000-01-01T02:00Z")]);
const T = x.ticks(); // [2000-01-01T00:00Z, 2000-01-01T00:15Z, 2000-01-01T00:30Z, …]
const f = x.tickFormat();
T.map(f); // ["2000", "12:15", "12:30", "12:45", "01 AM", "01:15", "01:30", "01:45", "02 AM"]
```

The specified _count_ is currently ignored, but is accepted for consistency with other scales such as [_linear_.tickFormat](https://d3js.org/d3-scale/linear#linear_tickFormat). If a format _specifier_ is specified, this method is equivalent to [format](https://d3js.org/d3-time-format#timeFormat). If _specifier_ is not specified, the default time format is returned. The default multi-scale time format chooses a human-readable representation based on the specified date as follows:

- `%Y` \- for year boundaries, such as `2011`.
- `%B` \- for month boundaries, such as `February`.
- `%b %d` \- for week boundaries, such as `Feb 06`.
- `%a %d` \- for day boundaries, such as `Mon 07`.
- `%I %p` \- for hour boundaries, such as `01 AM`.
- `%I:%M` \- for minute boundaries, such as `01:23`.
- `:%S` \- for second boundaries, such as `:45`.
- `.%L` \- milliseconds for all other times, such as `.012`.

Although somewhat unusual, this default behavior has the benefit of providing both local and global context: for example, formatting a sequence of ticks as \[11 PM, Mon 07, 01 AM\] reveals information about hours, dates, and day simultaneously, rather than just the hours \[11 PM, 12 AM, 01 AM\]. See [d3-time-format](https://d3js.org/d3-time-format) if you’d like to roll your own conditional time format.

## _time_.nice( _count_) [​](https://d3js.org/d3-scale/time\#time_nice)

[Examples](https://observablehq.com/@d3/d3-scaletime) · [Source](https://github.com/d3/d3-scale/blob/main/src/time.js) · Extends the domain so that it starts and ends on nice round values.

js

```
const x = d3.scaleUtc().domain([new Date("2000-01-01T12:34Z"), new Date("2000-01-01T12:59Z")]).nice();
x.domain(); // [2000-01-01T12:30Z, 2000-01-01T13:00Z]
```

This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value. See [_linear_.nice](https://d3js.org/d3-scale/linear#linear_nice) for more.

An optional tick _count_ argument allows greater control over the step size used to extend the bounds, guaranteeing that the returned [ticks](https://d3js.org/d3-scale/time#time_ticks) will exactly cover the domain. Alternatively, a [time _interval_](https://d3js.org/d3-time#timeInterval) may be specified to explicitly set the ticks. If an _interval_ is specified, an optional _step_ may also be specified to skip some ticks. For example, _time_.nice(d3.utcSecond.every(10)) will extend the domain to an even ten seconds (0, 10, 20, _etc._). See [_time_.ticks](https://d3js.org/d3-scale/time#time_ticks) and [_interval_.every](https://d3js.org/d3-time#interval_every) for further detail.

Nicing is useful if the domain is computed from data, say using [extent](https://d3js.org/d3-array/summarize#extent), and may be irregular. For example, for a domain of \[2009-07-13T00:02, 2009-07-13T23:48\], the nice domain is \[2009-07-13, 2009-07-14\]. If the domain has more than two values, nicing the domain only affects the first and last value.

## D3.js Contour Polygons
[Skip to content](https://d3js.org/d3-contour/contour#VPContent)

On this page

# Contour polygons [​](https://d3js.org/d3-contour/contour\#contour-polygons)

For each [threshold value](https://d3js.org/d3-contour/contour#contours_thresholds), the [contour generator](https://d3js.org/d3-contour/contour#_contours) 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](https://raw.githubusercontent.com/d3/d3-contour/main/img/temperature.png)](https://observablehq.com/@d3/geotiff-contours)

[![Cloud Contours](https://raw.githubusercontent.com/d3/d3-contour/main/img/clouds.png)](https://observablehq.com/@d3/cloud-contours)

Since the contour polygons are GeoJSON, you can transform and display them using standard tools; see [geoPath](https://d3js.org/d3-geo/path#geoPath), [geoProject](https://github.com/d3/d3-geo-projection/blob/main/README.md#geoProject) and [geoStitch](https://github.com/d3/d3-geo-projection/blob/main/README.md#geoStitch), for example. Here the above contours of surface temperature are displayed in the Natural Earth projection:

[![GeoTiff Contours II](https://raw.githubusercontent.com/d3/d3-contour/main/img/reprojection.png)](https://observablehq.com/@d3/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](https://raw.githubusercontent.com/d3/d3-contour/main/img/goldstein-price.png)](https://observablehq.com/@d3/contours)

[![Animated Contours](https://raw.githubusercontent.com/d3/d3-contour/main/img/sin-cos.png)](https://observablehq.com/@d3/animated-contours)

## contours() [​](https://d3js.org/d3-contour/contour\#contours)

[Examples](https://observablehq.com/collection/@d3/d3-contour) · [Source](https://github.com/d3/d3-contour/blob/main/src/contours.js) · Constructs a new contour generator with the default settings.

js

```
const contours = d3.contours()
    .size([width, height])
    .thresholds([0, 1, 2, 3, 4]);
```

## _contours_( _values_) [​](https://d3js.org/d3-contour/contour\#_contours)

[Source](https://github.com/d3/d3-contour/blob/main/src/contours.js) · Computes the contours for the given array of _values_, returning an array of [GeoJSON](http://geojson.org/geojson-spec.html) [MultiPolygon](http://geojson.org/geojson-spec.html#multipolygon) [geometry objects](http://geojson.org/geojson-spec.html#geometry-objects).

js

```
const polygons = contours(grid);
```

Each geometry object represents the area where the input _values_ are greater than or equal to the corresponding [threshold value](https://d3js.org/d3-contour/contour#contours_thresholds); 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](https://d3js.org/d3-contour/contour#contours_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](https://en.wikipedia.org/wiki/Test_functions_for_optimization) where -2 ≤ _x_ ≤ 2 and -2 ≤ _y_ ≤ 1:

js

```
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);
  }
}
```

js

```
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 [geoPath](https://d3js.org/d3-geo/path) to display, using null or [geoIdentity](https://d3js.org/d3-geo/projection#geoIdentity) as the associated projection.

## _contours_.contour( _values_, _threshold_) [​](https://d3js.org/d3-contour/contour\#contours_contour)

[Source](https://github.com/d3/d3-contour/blob/main/src/contours.js) · Computes a single contour, returning a [GeoJSON](http://geojson.org/geojson-spec.html) [MultiPolygon](http://geojson.org/geojson-spec.html#multipolygon) [geometry object](http://geojson.org/geojson-spec.html#geometry-objects) representing the area where the input _values_ are greater than or equal to the given [_threshold_ value](https://d3js.org/d3-contour/contour#contours_thresholds); 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](https://d3js.org/d3-contour/contour#contours_size); furthermore, each _values_\[ _i_ \+ _jn_\] must represent the value at the position ⟨ _i_, _j_⟩. See [_contours_](https://d3js.org/d3-contour/contour#_contours) for an example.

## _contours_.size( _size_) [​](https://d3js.org/d3-contour/contour\#contours_size)

[Source](https://github.com/d3/d3-contour/blob/main/src/contours.js) · If _size_ is specified, sets the expected size of the input _values_ grid to the [contour generator](https://d3js.org/d3-contour/contour#_contours) 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_) [​](https://d3js.org/d3-contour/contour\#contours_smooth)

[Examples](https://observablehq.com/@d3/contours-smooth) · [Source](https://github.com/d3/d3-contour/blob/main/src/contours.js) · 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_) [​](https://d3js.org/d3-contour/contour\#contours_thresholds)

[Source](https://github.com/d3/d3-contour/blob/main/src/contours.js) · 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](https://d3js.org/d3-array/bin#thresholdSturges).

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](https://d3js.org/d3-array/summarize#extent) will be uniformly divided into approximately _count_ bins; see [ticks](https://d3js.org/d3-array/ticks#ticks).

## D3.js Partition Layout
[Skip to content](https://d3js.org/d3-hierarchy/partition#VPContent)

On this page

# Partition [​](https://d3js.org/d3-hierarchy/partition\#Partition)

[![Partition](https://raw.githubusercontent.com/d3/d3-hierarchy/main/img/partition.png)](https://observablehq.com/@d3/icicle/2)

[Examples](https://observablehq.com/@d3/icicle/2) · The partition layout produces adjacency diagrams: a space-filling variant of a [node-link tree diagram](https://d3js.org/d3-hierarchy/tree). Rather than drawing a link between parent and child in the hierarchy, nodes are drawn as solid areas (either arcs or rectangles), and their placement relative to other nodes reveals their position in the hierarchy. The size of the nodes encodes a quantitative dimension that would be difficult to show in a node-link diagram.

## partition() [​](https://d3js.org/d3-hierarchy/partition\#partition)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/partition.js) · Creates a new partition layout with the default settings.

## _partition_( _root_) [​](https://d3js.org/d3-hierarchy/partition\#_partition)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/partition.js) · Lays out the specified _root_ [hierarchy](https://d3js.org/d3-hierarchy/hierarchy), assigning the following properties on _root_ and its descendants:

- _node_.x0 - the left edge of the rectangle
- _node_.y0 - the top edge of the rectangle
- _node_.x1 - the right edge of the rectangle
- _node_.y1 - the bottom edge of the rectangle

You must call [_root_.sum](https://d3js.org/d3-hierarchy/hierarchy#node_sum) before passing the hierarchy to the partition layout. You probably also want to call [_root_.sort](https://d3js.org/d3-hierarchy/hierarchy#node_sort) to order the hierarchy before computing the layout.

## _partition_.size( _size_) [​](https://d3js.org/d3-hierarchy/partition\#partition_size)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/partition.js) · If _size_ is specified, sets this partition layout’s size to the specified two-element array of numbers \[ _width_, _height_\] and returns this partition layout. If _size_ is not specified, returns the current size, which defaults to \[1, 1\].

## _partition_.round( _round_) [​](https://d3js.org/d3-hierarchy/partition\#partition_round)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/partition.js) · If _round_ is specified, enables or disables rounding according to the given boolean and returns this partition layout. If _round_ is not specified, returns the current rounding state, which defaults to false.

## _partition_.padding( _padding_) [​](https://d3js.org/d3-hierarchy/partition\#partition_padding)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/partition.js) · If _padding_ is specified, sets the padding to the specified number and returns this partition layout. If _padding_ is not specified, returns the current padding, which defaults to zero. The padding is used to separate a node’s adjacent children.

## D3 Drag Behavior
[Skip to content](https://d3js.org/d3-drag#VPContent)

On this page

# d3-drag [​](https://d3js.org/d3-drag\#d3-drag)

[Examples](https://observablehq.com/collection/@d3/d3-drag) · [Drag-and-drop](https://en.wikipedia.org/wiki/Drag_and_drop) is a popular interaction method for manipulating spatial elements: move the pointer to an object, press and hold to grab it, “drag” the object to a new location, and release to “drop”. D3’s drag behavior provides a flexible abstraction for drag-and-drop. For example, you can drag nodes in a [force-directed graph](https://d3js.org/d3-force):

[![Force-Directed Graph](https://raw.githubusercontent.com/d3/d3-drag/master/img/force-graph.png)](https://observablehq.com/@d3/force-directed-graph/2)

Or a simulation of colliding circles:

[![Force Dragging II](https://raw.githubusercontent.com/d3/d3-drag/master/img/force-collide.png)](https://observablehq.com/@d3/drag-collisions)

The drag behavior isn’t just for moving elements around; there are a variety of ways to respond to a drag gesture. For example, you can use it to lasso elements in a scatterplot, or to paint lines on a canvas:

[![Line Drawing](https://raw.githubusercontent.com/d3/d3-drag/master/img/drawing.png)](https://observablehq.com/@d3/draw-me)

The drag behavior can be combined with other behaviors, such as [d3-zoom](https://d3js.org/d3-zoom) for zooming:

[![Drag & Zoom II](https://raw.githubusercontent.com/d3/d3-drag/master/img/dots.png)](https://observablehq.com/@d3/drag-zoom)

The drag behavior is agnostic about the DOM, so you can use it with SVG, HTML or even Canvas! And you can extend it with advanced selection techniques, such as a Voronoi overlay or a closest-target search:

[![Circle Dragging IV](https://raw.githubusercontent.com/d3/d3-drag/master/img/voronoi.png)](https://observablehq.com/@d3/circle-dragging-iii)[![Circle Dragging II](https://raw.githubusercontent.com/d3/d3-drag/master/img/canvas.png)](https://observablehq.com/@d3/circle-dragging-ii)

The drag behavior unifies mouse and touch input and avoids browser quirks. In the future the drag behavior will support [Pointer Events](https://www.w3.org/TR/pointerevents/), too.

## drag() [​](https://d3js.org/d3-drag\#drag)

[Source](https://github.com/d3/d3-drag/blob/main/src/drag.js) · Creates a new drag behavior. The returned behavior, [_drag_](https://d3js.org/d3-drag#_drag), is both an object and a function, and is typically applied to selected elements via [_selection_.call](https://d3js.org/d3-selection/control-flow#selection_call).

js

```
const drag = d3.drag();
```

## _drag_( _selection_) [​](https://d3js.org/d3-drag\#_drag)

[Source](https://github.com/d3/d3-drag/blob/main/src/drag.js) · Applies this drag behavior to the specified [_selection_](https://d3js.org/d3-selection). This function is typically not invoked directly, and is instead invoked via [_selection_.call](https://d3js.org/d3-selection/control-flow#selection_call). For example, to instantiate a drag behavior and apply it to a selection:

js

```
d3.selectAll(".node").call(d3.drag().on("start", started));
```

Internally, the drag behavior uses [_selection_.on](https://d3js.org/d3-selection/events#selection_on) to bind the necessary event listeners for dragging. The listeners use the name `.drag`, so you can subsequently unbind the drag behavior as follows:

js

```
selection.on(".drag", null);
```

Applying the drag behavior also sets the [-webkit-tap-highlight-color](https://developer.apple.com/library/mac/documentation/AppleApplications/Reference/SafariWebContent/AdjustingtheTextSize/AdjustingtheTextSize.html#//apple_ref/doc/uid/TP40006510-SW5) style to transparent, disabling the tap highlight on iOS. If you want a different tap highlight color, remove or re-apply this style after applying the drag behavior.

## _drag_.container( _container_) [​](https://d3js.org/d3-drag\#drag_container)

[Source](https://github.com/d3/d3-drag/blob/main/src/drag.js) · If _container_ is specified, sets the container accessor to the specified object or function and returns the drag behavior. If _container_ is not specified, returns the current container accessor, which defaults to:

js

```
function container() {
  return this.parentNode;
}
```

The _container_ of a drag gesture determines the coordinate system of subsequent [drag events](https://d3js.org/d3-drag#drag-events), affecting _event_.x and _event_.y. The element returned by the container accessor is subsequently passed to [pointer](https://d3js.org/d3-selection/events#pointer) to determine the local coordinates of the pointer.

The default container accessor returns the parent node of the element in the originating selection (see [_drag_](https://d3js.org/d3-drag#_drag)) that received the initiating input event. This is often appropriate when dragging SVG or HTML elements, since those elements are typically positioned relative to a parent. For dragging graphical elements with a Canvas, however, you may want to redefine the container as the initiating element itself:

js

```
function container() {
  return this;
}
```

Alternatively, the container may be specified as the element directly, such as `drag.container(canvas)`.

## _drag_.filter( _filter_) [​](https://d3js.org/d3-drag\#drag_filter)

[Source](https://github.com/d3/d3-drag/blob/main/src/drag.js) · If _filter_ is specified, sets the event filter to the specified function and returns the drag behavior. If _filter_ is not specified, returns the current filter, which defaults to:

js

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

If the filter returns falsey, the initiating event is ignored and no drag gestures are 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.

## _drag_.touchable( _touchable_) [​](https://d3js.org/d3-drag\#drag_touchable)

[Source](https://github.com/d3/d3-drag/blob/main/src/drag.js) · If _touchable_ is specified, sets the touch support detector to the specified function and returns the drag behavior. If _touchable_ is not specified, returns the current touch support detector, which defaults to:

js

```
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 drag behavior is [applied](https://d3js.org/d3-drag#_drag). 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.

## _drag_.subject( _subject_) [​](https://d3js.org/d3-drag\#drag_subject)

[Source](https://github.com/d3/d3-drag/blob/main/src/drag.js) · If _subject_ is specified, sets the subject accessor to the specified object or function and returns the drag behavior. If _subject_ is not specified, returns the current subject accessor, which defaults to:

js

```
function subject(event, d) {
  return d == null ? {x: event.x, y: event.y} : d;
}
```

The _subject_ of a drag gesture represents _the thing being dragged_. It is computed when an initiating input event is received, such as a mousedown or touchstart, immediately before the drag gesture starts. The subject is then exposed as _event_.subject on subsequent [drag events](https://d3js.org/d3-drag#drag-events) for this gesture.

The default subject is the [datum](https://d3js.org/d3-selection/joining#selection_datum) of the element in the originating selection (see [_drag_](https://d3js.org/d3-drag#_drag)) that received the initiating input event; if this datum is undefined, an object representing the coordinates of the pointer is created. When dragging circle elements in SVG, the default subject is thus the datum of the circle being dragged. With [Canvas](https://html.spec.whatwg.org/multipage/scripting.html#the-canvas-element), the default subject is the canvas element’s datum (regardless of where on the canvas you click). In this case, a custom subject accessor would be more appropriate, such as one that picks the closest circle to the mouse within a given search _radius_:

js

```
function subject(event) {
  let n = circles.length,
      i,
      dx,
      dy,
      d2,
      s2 = radius * radius,
      circle,
      subject;

  for (i = 0; i < n; ++i) {
    circle = circles[i];
    dx = event.x - circle.x;
    dy = event.y - circle.y;
    d2 = dx * dx + dy * dy;
    if (d2 < s2) subject = circle, s2 = d2;
  }

  return subject;
}
```

TIP

If necessary, the above can be accelerated using [_quadtree_.find](https://d3js.org/d3-quadtree#quadtree_find), [_simulation_.find](https://d3js.org/d3-force/simulation#simulation_find) or [_delaunay_.find](https://d3js.org/d3-delaunay/delaunay#delaunay_find).

The returned subject should be an object that exposes `x` and `y` properties, so that the relative position of the subject and the pointer can be preserved during the drag gesture. If the subject is null or undefined, no drag gesture is started for this pointer; however, other starting touches may yet start drag gestures. See also [_drag_.filter](https://d3js.org/d3-drag#drag_filter).

The subject of a drag gesture may not be changed after the gesture starts. The subject accessor is invoked with the same context and arguments as [_selection_.on](https://d3js.org/d3-selection/events#selection_on) listeners: the current event ( `event`) and datum `d`, with the `this` context as the current DOM element. During the evaluation of the subject accessor, `event` is a beforestart [drag event](https://d3js.org/d3-drag#drag-events). Use _event_.sourceEvent to access the initiating input event and _event_.identifier to access the touch identifier. The _event_.x and _event_.y are relative to the [container](https://d3js.org/d3-drag#drag_container), and are computed using [pointer](https://d3js.org/d3-selection/events#pointer).

## _drag_.clickDistance( _distance_) [​](https://d3js.org/d3-drag\#drag_clickDistance)

[Source](https://github.com/d3/d3-drag/blob/main/src/drag.js) · If _distance_ is specified, sets the maximum distance that the mouse can move between mousedown and mouseup that will trigger a subsequent click event. If at any point between mousedown and mouseup the mouse is greater than or equal to _distance_ from its position on mousedown, the click event following mouseup will be suppressed. If _distance_ is not specified, returns the current distance threshold, which defaults to zero. The distance threshold is measured in client coordinates ( [_event_.clientX](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX) and [_event_.clientY](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY)).

## _drag_.on( _typenames_, _listener_) [​](https://d3js.org/d3-drag\#drag_on)

[Source](https://github.com/d3/d3-drag/blob/main/src/drag.js) · If _listener_ is specified, sets the event _listener_ for the specified _typenames_ and returns the drag behavior. 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](https://d3js.org/d3-selection/events#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 `drag.foo` and `drag.bar`; the name allows multiple listeners to be registered for the same _type_. The _type_ must be one of the following:

- `start` \- after a new pointer becomes active (on mousedown or touchstart).
- `drag` \- after an active pointer moves (on mousemove or touchmove).
- `end` \- after an active pointer becomes inactive (on mouseup, touchend or touchcancel).

See [_dispatch_.on](https://d3js.org/d3-dispatch#dispatch_on) for more.

Changes to registered listeners via _drag_.on during a drag gesture _do not affect_ the current drag gesture. Instead, you must use [_event_.on](https://d3js.org/d3-drag#event_on), which also allows you to register temporary event listeners for the current drag gesture. **Separate events are dispatched for each active pointer** during a drag gesture. For example, if simultaneously dragging multiple subjects with multiple fingers, a start event is dispatched for each finger, even if both fingers start touching simultaneously. See [Drag Events](https://d3js.org/d3-drag#drag-events) for more.

## dragDisable( _window_) [​](https://d3js.org/d3-drag\#dragDisable)

[Source](https://github.com/d3/d3-drag/blob/main/src/nodrag.js) · Prevents native drag-and-drop and text selection on the specified _window_. As an alternative to preventing the default action of mousedown events (see [#9](https://github.com/d3/d3-drag/issues/9)), this method prevents undesirable default actions following mousedown. In supported browsers, this means capturing dragstart and selectstart events, preventing the associated default actions, and immediately stopping their propagation. In browsers that do not support selection events, the user-select CSS property is set to none on the document element. This method is intended to be called on mousedown, followed by [dragEnable](https://d3js.org/d3-drag#dragEnable) on mouseup.

## dragEnable( _window_, _noclick_) [​](https://d3js.org/d3-drag\#dragEnable)

[Source](https://github.com/d3/d3-drag/blob/main/src/nodrag.js) · Allows native drag-and-drop and text selection on the specified _window_; undoes the effect of [dragDisable](https://d3js.org/d3-drag#dragDisable). This method is intended to be called on mouseup, preceded by [dragDisable](https://d3js.org/d3-drag#dragDisable) on mousedown. If _noclick_ is true, this method also temporarily suppresses click events. The suppression of click events expires after a zero-millisecond timeout, such that it only suppress the click event that would immediately follow the current mouseup event, if any.

## Drag events [​](https://d3js.org/d3-drag\#drag-events)

When a [drag event listener](https://d3js.org/d3-drag#drag_on) is invoked, it receives the current drag event as its first argument. The _event_ object exposes several fields:

- `target` \- the associated [drag behavior](https://d3js.org/d3-drag#drag).
- `type` \- the string “start”, “drag” or “end”; see [_drag_.on](https://d3js.org/d3-drag#drag_on).
- `subject` \- the drag subject, defined by [_drag_.subject](https://d3js.org/d3-drag#drag_subject).
- `x` \- the new _x_-coordinate of the subject; see [_drag_.container](https://d3js.org/d3-drag#drag_container).
- `y` \- the new y coordinate of the subject; see [_drag_.container](https://d3js.org/d3-drag#drag_container).
- `dx` \- the change in _x_-coordinate since the previous drag event.
- `dy` \- the change in y coordinate since the previous drag event.
- `identifier` \- the string “mouse”, or a numeric [touch identifier](https://www.w3.org/TR/touch-events/#widl-Touch-identifier).
- `active` \- the number of currently active drag gestures (on start and end, not including this one).
- `sourceEvent` \- the underlying input event, such as mousemove or touchmove.

The _event_.active field is useful for detecting the first start event and the last end event in a sequence of concurrent drag gestures: it is zero when the first drag gesture starts, and zero when the last drag gesture ends.

The _event_ object also exposes the [_event_.on](https://d3js.org/d3-drag#event_on) method.

This table describes how the drag behavior interprets native events:

| Event | Listening Element | Drag Event | Default Prevented? |
| --- | --- | --- | --- |
| mousedown⁵ | selection | start | no¹ |
| mousemove² | window¹ | drag | yes |
| mouseup² | window¹ | end | yes |
| dragstart² | window | - | yes |
| selectstart² | window | - | yes |
| click³ | window | - | yes |
| touchstart | selection | start | no⁴ |
| touchmove | selection | drag | yes |
| touchend | selection | end | no⁴ |
| touchcancel | selection | end | no⁴ |

The propagation of all consumed events is [immediately stopped](https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation). If you want to prevent some events from initiating a drag gesture, use [_drag_.filter](https://d3js.org/d3-drag#drag_filter).

¹ Necessary to capture events outside an iframe; see [#9](https://github.com/d3/d3-drag/issues/9).

² Only applies during an active, mouse-based gesture; see [#9](https://github.com/d3/d3-drag/issues/9).

³ Only applies immediately after some mouse-based gestures; see [_drag_.clickDistance](https://d3js.org/d3-drag#drag_clickDistance).

⁴ Necessary to allow [click emulation](https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW7) on touch input; see [#9](https://github.com/d3/d3-drag/issues/9).

⁵ Ignored if within 500ms of a touch gesture ending; assumes [click emulation](https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW7).

## _event_.on( _typenames_, _listener_) [​](https://d3js.org/d3-drag\#event_on)

[Source](https://github.com/d3/d3-drag/blob/main/src/event.js) · Equivalent to [_drag_.on](https://d3js.org/d3-drag#drag_on), but only applies to the current drag gesture. Before the drag gesture starts, a [copy](https://d3js.org/d3-dispatch#dispatch_copy) of the current drag [event listeners](https://d3js.org/d3-drag#drag_on) is made. This copy is bound to the current drag gesture and modified by _event_.on. This is useful for temporary listeners that only receive events for the current drag gesture. For example, this start event listener registers temporary drag and end event listeners as closures:

js

```
function started(event) {
  const circle = d3.select(this).classed("dragging", true);
  const dragged = (event, d) => circle.raise().attr("cx", d.x = event.x).attr("cy", d.y = event.y);
  const ended = () => circle.classed("dragging", false);
  event.on("drag", dragged).on("end", ended);
}
```

## Delaunay Triangulations
[Skip to content](https://d3js.org/d3-delaunay/delaunay#VPContent)

On this page

# Delaunay triangulations [​](https://d3js.org/d3-delaunay/delaunay\#delaunay-triangulations)

The Delaunay triangulation is a triangular mesh formed from a set of points in _x_ and _y_. No point is inside the circumcircle of any triangle, which is a nice geometric property for certain applications, and tends to avoid “sliver” triangles. The Delaunay triangulation is the dual of the [Voronoi diagram](https://d3js.org/d3-delaunay/voronoi).

## new Delaunay( _points_) [​](https://d3js.org/d3-delaunay/delaunay\#Delaunay)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Returns the Delaunay triangulation for the given flat array \[ _x0_, _y0_, _x1_, _y1_, …\] of _points_.

js

```
const delaunay = new d3.Delaunay(Float64Array.of(0, 0, 0, 1, 1, 0, 1, 1));
```

The given _points_ may be any array-like type, but is typically a Float64Array.

### _delaunay_.points [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_points)

The coordinates of the points as an array \[ _x0_, _y0_, _x1_, _y1_, …\].

### _delaunay_.halfedges [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_halfedges)

The halfedge indexes as an Int32Array \[ _j0_, _j1_, …\]. For each index 0 ≤ _i_ < _halfedges_.length, there is a halfedge from triangle vertex _j_ = _halfedges_\[ _i_\] to triangle vertex _i_. Equivalently, this means that triangle ⌊ _i_ / 3⌋ is adjacent to triangle ⌊ _j_ / 3⌋. If _j_ is negative, then triangle ⌊ _i_ / 3⌋ is an exterior triangle on the [convex hull](https://d3js.org/d3-delaunay/delaunay#delaunay_hull). For example, to render the internal edges of the Delaunay triangulation:

js

```
const {points, halfedges, triangles} = delaunay;
for (let i = 0, n = halfedges.length; i < n; ++i) {
  const j = halfedges[i];
  if (j < i) continue;
  const ti = triangles[i];
  const tj = triangles[j];
  context.moveTo(points[ti * 2], points[ti * 2 + 1]);
  context.lineTo(points[tj * 2], points[tj * 2 + 1]);
}
```

See also [_delaunay_.render](https://d3js.org/d3-delaunay/delaunay#delaunay_render).

### _delaunay_.hull [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_hull)

An Int32Array of point indexes that form the convex hull in counterclockwise order. If the points are collinear, returns them ordered.

See also [_delaunay_.renderHull](https://d3js.org/d3-delaunay/delaunay#delaunay_renderHull).

### _delaunay_.triangles [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_triangles)

The triangle vertex indexes as an Uint32Array \[ _i0_, _j0_, _k0_, _i1_, _j1_, _k1_, …\]. Each contiguous triplet of indexes _i_, _j_, _k_ forms a counterclockwise triangle. The coordinates of the triangle’s points can be found by going through [_delaunay_.points](https://d3js.org/d3-delaunay/delaunay#delaunay_points). For example, to render triangle _i_:

js

```
const {points, triangles} = delaunay;
const t0 = triangles[i * 3 + 0];
const t1 = triangles[i * 3 + 1];
const t2 = triangles[i * 3 + 2];
context.moveTo(points[t0 * 2], points[t0 * 2 + 1]);
context.lineTo(points[t1 * 2], points[t1 * 2 + 1]);
context.lineTo(points[t2 * 2], points[t2 * 2 + 1]);
context.closePath();
```

See also [_delaunay_.renderTriangle](https://d3js.org/d3-delaunay/delaunay#delaunay_renderTriangle).

### _delaunay_.inedges [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_inedges)

The incoming halfedge indexes as a Int32Array \[ _e0_, _e1_, _e2_, …\]. For each point _i_, _inedges_\[ _i_\] is the halfedge index _e_ of an incoming halfedge. For coincident points, the halfedge index is -1; for points on the convex hull, the incoming halfedge is on the convex hull; for other points, the choice of incoming halfedge is arbitrary. The _inedges_ table can be used to traverse the Delaunay triangulation; see also [_delaunay_.neighbors](https://d3js.org/d3-delaunay/delaunay#delaunay_neighbors).

## Delaunay.from( _points_, _fx_, _fy_, _that_) [​](https://d3js.org/d3-delaunay/delaunay\#Delaunay_from)

TIP

Delaunay.from is typically slower than [new Delaunay](https://d3js.org/d3-delaunay/delaunay#Delaunay) because it requires materializing a new flat array of _xy_ coordinates.

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Returns the Delaunay triangulation for the given array or iterable of _points_. If _fx_ and _fy_ are not specified, then _points_ is assumed to be an array of two-element arrays of numbers: \[\[ _x0_, _y0_\], \[ _x1_, _y1_\], …\].

js

```
const delaunay = d3.Delaunay.from([[0, 0], [0, 1], [1, 0], [1, 1]]);
```

Otherwise, _fx_ and _fy_ are functions that are invoked for each element in the _points_ array in order, and must return the respective x and y coordinate for each point.

js

```
const delaunay = d3.Delaunay.from([{x: 0, y: 0}, {x: 0, y: 1}, {x: 1, y: 0}, {x: 1, y: 1}], (d) => d.x, (d) => d.y);
```

If _that_ is specified, the functions _fx_ and _fy_ are invoked with _that_ as _this_. (See [Array.from](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/from) for reference.)

## _delaunay_.find( _x_, _y_, _i_) [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_find)

js

```
delaunay.find(0, 0) // 353
```

[Examples](https://observablehq.com/@d3/delaunay-find) · [Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Returns the index of the input point that is closest to the specified point ⟨ _x_, _y_⟩. The search is started at the specified point _i_. If _i_ is not specified, it defaults to zero.

## _delaunay_.neighbors( _i_) [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_neighbors)

js

```
delaunay.neighbors(353) // [813, 712, 521, 351, 358, 384]
```

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Returns an iterable over the indexes of the neighboring points to the specified point _i_. The iterable is empty if _i_ is a coincident point.

## _delaunay_.render( _context_) [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_render)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Renders the edges of the Delaunay triangulation to the specified _context_. The specified _context_ must implement the _context_.moveTo and _context_.lineTo methods from the [CanvasPathMethods API](https://www.w3.org/TR/2dcontext/#canvaspathmethods). If a _context_ is not specified, an SVG path string is returned instead.

## _delaunay_.renderHull( _context_) [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_renderHull)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Renders the convex hull of the Delaunay triangulation to the specified _context_. The specified _context_ must implement the _context_.moveTo and _context_.lineTo methods from the [CanvasPathMethods API](https://www.w3.org/TR/2dcontext/#canvaspathmethods). If a _context_ is not specified, an SVG path string is returned instead.

## _delaunay_.renderTriangle( _i_, _context_) [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_renderTriangle)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Renders triangle _i_ of the Delaunay triangulation to the specified _context_. The specified _context_ must implement the _context_.moveTo, _context_.lineTo and _context_.closePath methods from the [CanvasPathMethods API](https://www.w3.org/TR/2dcontext/#canvaspathmethods). If a _context_ is not specified, an SVG path string is returned instead.

## _delaunay_.renderPoints( _context_, _radius_) [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_renderPoints)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Renders the input points of the Delaunay triangulation to the specified _context_ as circles with the specified _radius_. If _radius_ is not specified, it defaults to 2. The specified _context_ must implement the _context_.moveTo and _context_.arc methods from the [CanvasPathMethods API](https://www.w3.org/TR/2dcontext/#canvaspathmethods). If a _context_ is not specified, an SVG path string is returned instead.

## _delaunay_.hullPolygon() [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_hullPolygon)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Returns the closed polygon \[\[ _x0_, _y0_\], \[ _x1_, _y1_\], …, \[ _x0_, _y0_\]\] representing the convex hull. See also [_delaunay_.renderHull](https://d3js.org/d3-delaunay/delaunay#delaunay_renderHull).

## _delaunay_.trianglePolygons() [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_trianglePolygons)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Returns an iterable over the [polygons for each triangle](https://d3js.org/d3-delaunay/delaunay#delaunay_trianglePolygon), in order. See also [_delaunay_.renderTriangle](https://d3js.org/d3-delaunay/delaunay#delaunay_renderTriangle).

## _delaunay_.trianglePolygon( _i_) [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_trianglePolygon)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Returns the closed polygon \[\[ _x0_, _y0_\], \[ _x1_, _y1_\], \[ _x2_, _y2_\], \[ _x0_, _y0_\]\] representing the triangle _i_. See also [_delaunay_.renderTriangle](https://d3js.org/d3-delaunay/delaunay#delaunay_renderTriangle).

## _delaunay_.update() [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_update)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Recomputes the triangulation after the points have been modified in-place.

## _delaunay_.voronoi( _bounds_) [​](https://d3js.org/d3-delaunay/delaunay\#delaunay_voronoi)

[Source](https://github.com/d3/d3-delaunay/blob/main/src/delaunay.js) · Returns the [Voronoi diagram](https://d3js.org/d3-delaunay/voronoi) for the given Delaunay triangulation. When rendering, the diagram will be clipped to the specified _bounds_ = \[ _xmin_, _ymin_, _xmax_, _ymax_\].

js

```
const delaunay = d3.Delaunay.from(points);
const voronoi = delaunay.voronoi([0, 0, 640, 480]);
```

If _bounds_ is not specified, it defaults to \[0, 0, 960, 500\]. The Voronoi diagram is returned even in degenerate cases where no triangulation exists — namely 0, 1 or 2 points, and collinear points.

## D3 Contour Module
[Skip to content](https://d3js.org/d3-contour#VPContent)

Return to top

# d3-contour [​](https://d3js.org/d3-contour\#d3-contour)

[Fork ↗︎](https://observablehq.com/@d3/volcano-contours/2)

This module computes contour polygons by applying [marching squares](https://en.wikipedia.org/wiki/Marching_squares) to a rectangular grid of numeric values. For example, the contours above show the topography of [Maungawhau](https://en.wikipedia.org/wiki/Maungawhau_/_Mount_Eden).

See one of:

- [Contours](https://d3js.org/d3-contour/contour)
- [Density estimation](https://d3js.org/d3-contour/density)

## Array Transformation Methods
[Skip to content](https://d3js.org/d3-array/transform#VPContent)

On this page

# Transforming data [​](https://d3js.org/d3-array/transform\#transforming-data)

Transform arrays and generate new arrays.

## cross(... _iterables_, _reducer_) [​](https://d3js.org/d3-array/transform\#cross)

[Examples](https://observablehq.com/@d3/d3-cross) · [Source](https://github.com/d3/d3-array/blob/main/src/cross.js) · Returns the [Cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) of the specified _iterables_.

js

```
d3.cross([1, 2], ["x", "y"]) // [[1, "x"], [1, "y"], [2, "x"], [2, "y"]]
```

If a _reducer_ is specified, it is invoked for each combination of elements from each of the given _iterables_, and returns the corresponding reduced value.

js

```
d3.cross([1, 2], ["x", "y"], (a, b) => a + b) // ["1x", "1y", "2x", "2y"]
```

## merge( _iterables_) [​](https://d3js.org/d3-array/transform\#merge)

[Examples](https://observablehq.com/@d3/d3-merge) · [Source](https://github.com/d3/d3-array/blob/main/src/merge.js) · Merges the specified iterable of _iterables_ into a new flat array. This method is similar to the built-in [_array_.concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) method, but is more convenient when you have an array of arrays or an iterable of iterables.

js

```
d3.merge([[1], [2, 3]]) // [1, 2, 3]
```

js

```
d3.merge(new Set([new Set([1]), new Set([2, 3])])) // [1, 2, 3]
```

## pairs( _iterable_, _reducer_) [​](https://d3js.org/d3-array/transform\#pairs)

[Examples](https://observablehq.com/@d3/d3-pairs) · [Source](https://github.com/d3/d3-array/blob/main/src/pairs.js) · Returns an array of adjacent pairs of elements from the specified _iterable_, in order. If the specified iterable has fewer than two elements, returns the empty array.

js

```
d3.pairs([1, 2, 3, 4]) // [[1, 2], [2, 3], [3, 4]]
```

If a _reducer_ function is specified, it is successively passed an element _i - 1_ and element _i_ from the _iterable_.

js

```
d3.pairs([1, 1, 2, 3, 5], (a, b) => b - a) // [0, 1, 1, 2]
```

## transpose( _matrix_) [​](https://d3js.org/d3-array/transform\#transpose)

[Examples](https://observablehq.com/@d3/d3-transpose) · [Source](https://github.com/d3/d3-array/blob/main/src/transpose.js) · Uses the [zip](https://d3js.org/d3-array/transform#zip) operator as a two-dimensional [matrix transpose](http://en.wikipedia.org/wiki/Transpose).

js

```
d3.transpose([["Alice", "Bob", "Carol"], [32, 13, 14]]) // [["Alice", 32], ["Bob", 13], ["Carol", 14]]
```

js

```
d3.transpose([["Alice", 32], ["Bob", 13], ["Carol", 14]]) // [["Alice", "Bob", "Carol"], [32, 13, 14]]
```

## zip(... _arrays_) [​](https://d3js.org/d3-array/transform\#zip)

[Examples](https://observablehq.com/@d3/d3-transpose) · [Source](https://github.com/d3/d3-array/blob/main/src/zip.js) · Returns an array of arrays, where the _i_ th array contains the _i_ th element from each of the argument _arrays_. The returned array is truncated in length to the shortest array in _arrays_. If _arrays_ contains only a single array, the returned array contains one-element arrays. With no arguments, the returned array is empty.

js

```
d3.zip(["Alice", "Bob", "Carol"], [32, 13, 14]) // [["Alice", 32], ["Bob", 13], ["Carol", 14]]
```

## filter( _iterable_, _test_) [​](https://d3js.org/d3-array/transform\#filter)

[Source](https://github.com/d3/d3-array/blob/main/src/filter.js) · Returns a new array containing the values from _iterable_, in order, for which the given _test_ function returns true.

js

```
d3.filter(new Set([0, 2, 3, 4]), (d) => d & 1) // [3]
```

Like [_array_.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), but works with any iterable.

## map( _iterable_, _mapper_) [​](https://d3js.org/d3-array/transform\#map)

[Source](https://github.com/d3/d3-array/blob/main/src/map.js) · Returns a new array containing the mapped values from _iterable_, in order, as defined by given _mapper_ function.

js

```
d3.map(new Set([0, 2, 3, 4]), (d) => d & 1) // [0, 0, 1, 0]
```

Like [_array_.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), but works with any iterable.

## reduce( _iterable_, _reducer_, _initialValue_) [​](https://d3js.org/d3-array/transform\#reduce)

[Source](https://github.com/d3/d3-array/blob/main/src/reduce.js) · Returns the reduced value defined by given _reducer_ function, which is repeatedly invoked for each value in _iterable_, being passed the current reduced value and the next value.

js

```
d3.reduce(new Set([0, 2, 3, 4]), (p, v) => p + v, 0) // 9
```

Like [_array_.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce), but works with any iterable.

## D3 Path Module
[Skip to content](https://d3js.org/d3-path#VPContent)

On this page

# d3-path [​](https://d3js.org/d3-path\#d3-path)

[Examples](https://observablehq.com/@d3/d3-path) · Say you have some code that draws to a 2D canvas:

js

```
function drawCircle(context, radius) {
  context.moveTo(radius, 0);
  context.arc(0, 0, radius, 0, 2 * Math.PI);
}
```

The d3-path module lets you take this exact code and additionally render to [SVG](http://www.w3.org/TR/SVG/paths.html). It works by [serializing](https://d3js.org/d3-path#path_toString) [CanvasPathMethods](http://www.w3.org/TR/2dcontext/#canvaspathmethods) calls to [SVG path data](http://www.w3.org/TR/SVG/paths.html#PathData). For example:

js

```
const path = d3.path();
drawCircle(path, 40);
path.toString(); // "M40,0A40,40,0,1,1,-40,0A40,40,0,1,1,40,0"
```

Now code you write once can be used with both Canvas (for performance) and SVG (for convenience). For a practical example, see [d3-shape](https://d3js.org/d3-shape).

## path() [​](https://d3js.org/d3-path\#path)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Constructs a new path serializer that implements [CanvasPathMethods](http://www.w3.org/TR/2dcontext/#canvaspathmethods).

## _path_.moveTo( _x_, _y_) [​](https://d3js.org/d3-path\#path_moveTo)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Move to the specified point ⟨ _x_, _y_⟩. Equivalent to [_context_.moveTo](http://www.w3.org/TR/2dcontext/#dom-context-2d-moveto) and SVG’s [“moveto” command](http://www.w3.org/TR/SVG/paths.html#PathDataMovetoCommands).

js

```
path.moveTo(100, 100);
```

## _path_.closePath() [​](https://d3js.org/d3-path\#path_closePath)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Ends the current subpath and causes an automatic straight line to be drawn from the current point to the initial point of the current subpath. Equivalent to [_context_.closePath](http://www.w3.org/TR/2dcontext/#dom-context-2d-closepath) and SVG’s [“closepath” command](http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand).

js

```
path.closePath();
```

## _path_.lineTo( _x_, _y_) [​](https://d3js.org/d3-path\#path_lineTo)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Draws a straight line from the current point to the specified point ⟨ _x_, _y_⟩. Equivalent to [_context_.lineTo](http://www.w3.org/TR/2dcontext/#dom-context-2d-lineto) and SVG’s [“lineto” command](http://www.w3.org/TR/SVG/paths.html#PathDataLinetoCommands).

js

```
path.lineTo(200, 200);
```

## _path_.quadraticCurveTo( _cpx_, _cpy_, _x_, _y_) [​](https://d3js.org/d3-path\#path_quadraticCurveTo)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Draws a quadratic Bézier segment from the current point to the specified point ⟨ _x_, _y_⟩, with the specified control point ⟨ _cpx_, _cpy_⟩. Equivalent to [_context_.quadraticCurveTo](http://www.w3.org/TR/2dcontext/#dom-context-2d-quadraticcurveto) and SVG’s [quadratic Bézier curve commands](http://www.w3.org/TR/SVG/paths.html#PathDataQuadraticBezierCommands).

js

```
path.quadraticCurveTo(200, 0, 200, 200);
```

## _path_.bezierCurveTo( _cpx1_, _cpy1_, _cpx2_, _cpy2_, _x_, _y_) [​](https://d3js.org/d3-path\#path_bezierCurveTo)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Draws a cubic Bézier segment from the current point to the specified point ⟨ _x_, _y_⟩, with the specified control points ⟨ _cpx1_, _cpy1_⟩ and ⟨ _cpx2_, _cpy2_⟩. Equivalent to [_context_.bezierCurveTo](http://www.w3.org/TR/2dcontext/#dom-context-2d-beziercurveto) and SVG’s [cubic Bézier curve commands](http://www.w3.org/TR/SVG/paths.html#PathDataCubicBezierCommands).

js

```
path.bezierCurveTo(200, 0, 0, 200, 200, 200);
```

## _path_.arcTo( _x1_, _y1_, _x2_, _y2_, _radius_) [​](https://d3js.org/d3-path\#path_arcTo)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Draws a circular arc segment with the specified _radius_ that starts tangent to the line between the current point and the specified point ⟨ _x1_, _y1_⟩ and ends tangent to the line between the specified points ⟨ _x1_, _y1_⟩ and ⟨ _x2_, _y2_⟩. If the first tangent point is not equal to the current point, a straight line is drawn between the current point and the first tangent point. Equivalent to [_context_.arcTo](http://www.w3.org/TR/2dcontext/#dom-context-2d-arcto) and uses SVG’s [elliptical arc curve commands](http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands).

js

```
path.arcTo(150, 150, 300, 10, 40);
```

## _path_.arc( _x_, _y_, _radius_, _startAngle_, _endAngle_, _anticlockwise_) [​](https://d3js.org/d3-path\#path_arc)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Draws a circular arc segment with the specified center ⟨ _x_, _y_⟩, _radius_, _startAngle_ and _endAngle_. If _anticlockwise_ is true, the arc is drawn in the anticlockwise direction; otherwise, it is drawn in the clockwise direction. If the current point is not equal to the starting point of the arc, a straight line is drawn from the current point to the start of the arc. Equivalent to [_context_.arc](http://www.w3.org/TR/2dcontext/#dom-context-2d-arc) and uses SVG’s [elliptical arc curve commands](http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands).

js

```
path.arc(80, 80, 70, 0, Math.PI * 2);
```

## _path_.rect( _x_, _y_, _w_, _h_) [​](https://d3js.org/d3-path\#path_rect)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Creates a new subpath containing just the four points ⟨ _x_, _y_⟩, ⟨ _x_ \+ _w_, _y_⟩, ⟨ _x_ \+ _w_, _y_ \+ _h_⟩, ⟨ _x_, _y_ \+ _h_⟩, with those four points connected by straight lines, and then marks the subpath as closed. Equivalent to [_context_.rect](http://www.w3.org/TR/2dcontext/#dom-context-2d-rect) and uses SVG’s [“lineto” commands](http://www.w3.org/TR/SVG/paths.html#PathDataLinetoCommands).

js

```
path.rect(10, 10, 140, 140);
```

## _path_.toString() [​](https://d3js.org/d3-path\#path_toString)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Returns the string representation of this _path_ according to SVG’s [path data specification](http://www.w3.org/TR/SVG/paths.html#PathData).

js

```
path.toString() // "M40,0A40,40,0,1,1,-40,0A40,40,0,1,1,40,0"
```

## pathRound( _digits_ = 3) [​](https://d3js.org/d3-path\#pathRound)

[Source](https://github.com/d3/d3-path/blob/main/src/path.js) · Like [path](https://d3js.org/d3-path#path), except limits the digits after the decimal to the specified number of _digits_. Useful for reducing the size of generated SVG path data.

js

```
const path = d3.pathRound(3);
```

## D3 Interpolation Methods
[Skip to content](https://d3js.org/d3-interpolate#VPContent)

Return to top

# d3-interpolate [​](https://d3js.org/d3-interpolate\#d3-interpolate)

This module provides a variety of interpolation methods for blending between two values. Values may be numbers, colors, strings, arrays, or even deeply-nested objects. For example:

js

```
const i = d3.interpolateNumber(10, 20);
i(0.0); // 10
i(0.2); // 12
i(0.5); // 15
i(1.0); // 20
```

The returned function `i` is an _interpolator_. Given a starting value _a_ and an ending value _b_, it takes a parameter _t_ typically in \[0, 1\] and returns the corresponding interpolated value. An interpolator typically returns a value equivalent to _a_ at _t_ = 0 and a value equivalent to _b_ at _t_ = 1.

You can interpolate more than just numbers. To find the perceptual midpoint between steelblue and brown:

js

```
d3.interpolateLab("steelblue", "brown")(0.5); // "rgb(142, 92, 109)"
```

Or, as a color ramp from _t_ = 0 to _t_ = 1:

Here’s a more elaborate example demonstrating type inference used by [interpolate](https://d3js.org/d3-interpolate/value#interpolate):

js

```
const i = d3.interpolate({colors: ["red", "blue"]}, {colors: ["white", "black"]});
i(0.0); // {colors: ["rgb(255, 0, 0)", "rgb(0, 0, 255)"]}
i(0.5); // {colors: ["rgb(255, 128, 128)", "rgb(0, 0, 128)"]}
i(1.0); // {colors: ["rgb(255, 255, 255)", "rgb(0, 0, 0)"]}
```

Note that the generic value interpolator detects not only nested objects and arrays, but also color strings and numbers embedded in strings!

See one of:

- [Value interpolation](https://d3js.org/d3-interpolate/value)
- [Color interpolation](https://d3js.org/d3-interpolate/color)
- [Transform interpolation](https://d3js.org/d3-interpolate/transform)
- [Zoom interpolation](https://d3js.org/d3-interpolate/zoom)

## D3.js Hierarchical Data
[Skip to content](https://d3js.org/d3-hierarchy/stratify#VPContent)

On this page

# Stratify [​](https://d3js.org/d3-hierarchy/stratify\#Stratify)

[Examples](https://observablehq.com/@d3/d3-stratify) · Consider the following table of relationships:

| Name | Parent |
| --- | --- |
| Eve |  |
| Cain | Eve |
| Seth | Eve |
| Enos | Seth |
| Noam | Seth |
| Abel | Eve |
| Awan | Eve |
| Enoch | Awan |
| Azura | Eve |

These names are conveniently unique, so we can unambiguously represent the hierarchy as a CSV file:

```
name,parent
Eve,
Cain,Eve
Seth,Eve
Enos,Seth
Noam,Seth
Abel,Eve
Awan,Eve
Enoch,Awan
Azura,Eve
```

To parse the CSV using [csvParse](https://d3js.org/d3-dsv#csvParse):

js

```
const table = d3.csvParse(text);
```

This returns an array of { _name_, _parent_} objects:

json

```
[\
  {"name": "Eve",   "parent": ""},\
  {"name": "Cain",  "parent": "Eve"},\
  {"name": "Seth",  "parent": "Eve"},\
  {"name": "Enos",  "parent": "Seth"},\
  {"name": "Noam",  "parent": "Seth"},\
  {"name": "Abel",  "parent": "Eve"},\
  {"name": "Awan",  "parent": "Eve"},\
  {"name": "Enoch", "parent": "Awan"},\
  {"name": "Azura", "parent": "Eve"}\
]
```

To convert to a [hierarchy](https://d3js.org/d3-hierarchy/hierarchy):

js

```
const root = d3.stratify()
    .id((d) => d.name)
    .parentId((d) => d.parent)
  (table);
```

This hierarchy can now be passed to a hierarchical layout, such as [tree](https://d3js.org/d3-hierarchy/tree), for visualization.

The stratify operator also works with [delimited paths](https://d3js.org/d3-hierarchy/stratify#stratify_path) as is common in file systems.

## stratify() [​](https://d3js.org/d3-hierarchy/stratify\#stratify)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/stratify.js) · Constructs a new stratify operator with the default settings.

js

```
const stratify = d3.stratify();
```

## _stratify_( _data_) [​](https://d3js.org/d3-hierarchy/stratify\#_stratify)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/stratify.js) · Generates a new hierarchy from the specified tabular _data_.

js

```
const root = stratify(data);
```

## _stratify_.id( _id_) [​](https://d3js.org/d3-hierarchy/stratify\#stratify_id)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/stratify.js) · If _id_ is specified, sets the id accessor to the given function and returns this stratify operator. Otherwise, returns the current id accessor, which defaults to:

js

```
function id(d) {
  return d.id;
}
```

The id accessor is invoked for each element in the input data passed to the [stratify operator](https://d3js.org/d3-hierarchy/stratify#_stratify), being passed the current datum ( _d_) and the current index ( _i_). The returned string is then used to identify the node’s relationships in conjunction with the [parent id](https://d3js.org/d3-hierarchy/stratify#stratify_parentId). For leaf nodes, the id may be undefined; otherwise, the id must be unique. (Null and the empty string are equivalent to undefined.)

## _stratify_.parentId( _parentId_) [​](https://d3js.org/d3-hierarchy/stratify\#stratify_parentId)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/stratify.js) · If _parentId_ is specified, sets the parent id accessor to the given function and returns this stratify operator. Otherwise, returns the current parent id accessor, which defaults to:

js

```
function parentId(d) {
  return d.parentId;
}
```

The parent id accessor is invoked for each element in the input data passed to the [stratify operator](https://d3js.org/d3-hierarchy/stratify#_stratify), being passed the current datum ( _d_) and the current index ( _i_). The returned string is then used to identify the node’s relationships in conjunction with the [id](https://d3js.org/d3-hierarchy/stratify#stratify_id). For the root node, the parent id should be undefined. (Null and the empty string are equivalent to undefined.) There must be exactly one root node in the input data, and no circular relationships.

## _stratify_.path( _path_) [​](https://d3js.org/d3-hierarchy/stratify\#stratify_path)

[Source](https://github.com/d3/d3-hierarchy/blob/main/src/stratify.js) · If _path_ is specified, sets the path accessor to the given function and returns this stratify operator. Otherwise, returns the current path accessor, which defaults to undefined.

If a path accessor is set, the [id](https://d3js.org/d3-hierarchy/stratify#stratify_id) and [parentId](https://d3js.org/d3-hierarchy/stratify#stratify_parentId) accessors are ignored, and a unix-like hierarchy is computed on the slash-delimited strings returned by the path accessor, imputing parent nodes and ids as necessary.

For example, given the output of the UNIX find command in the local directory:

js

```
const paths = [\
  "axes.js",\
  "channel.js",\
  "context.js",\
  "legends.js",\
  "legends/ramp.js",\
  "marks/density.js",\
  "marks/dot.js",\
  "marks/frame.js",\
  "scales/diverging.js",\
  "scales/index.js",\
  "scales/ordinal.js",\
  "stats.js",\
  "style.js",\
  "transforms/basic.js",\
  "transforms/bin.js",\
  "transforms/centroid.js",\
  "warnings.js",\
];
```

You can say:

js

```
const root = d3.stratify().path((d) => d)(paths);
```

## Number Formatting in D3
[Skip to content](https://d3js.org/d3-format#VPContent)

On this page

# d3-format [​](https://d3js.org/d3-format\#d3-format)

Ever noticed how sometimes JavaScript doesn’t display numbers the way you expect? Like, you tried to print tenths with a simple loop:

js

```
for (let i = 0; i < 10; ++i) {
  console.log(0.1 * i);
}
```

And you got this:

```
0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6000000000000001
0.7000000000000001
0.8
0.9
```

Welcome to [binary floating point](https://en.wikipedia.org/wiki/Double-precision_floating-point_format)! ಠ\_ಠ

Yet rounding error is not the only reason to customize number formatting. A table of numbers should be formatted consistently for comparison; above, 0.0 would be better than 0. Large numbers should have grouped digits (e.g., 42,000) or be in scientific or metric notation (4.2e+4, 42k). Currencies should have fixed precision ($3.50). Reported numerical results should be rounded to significant digits (4021 becomes 4000). Number formats should appropriate to the reader’s locale (42.000,00 or 42,000.00). The list goes on.

Formatting numbers for human consumption is the purpose of d3-format, which is modeled after Python 3’s [format specification mini-language](https://docs.python.org/3/library/string.html#format-specification-mini-language) ( [PEP 3101](https://www.python.org/dev/peps/pep-3101/)). Revisiting the example above:

js

```
const f = d3.format(".1f");
for (let i = 0; i < 10; ++i) {
  console.log(f(0.1 * i));
}
```

Now you get this:

```
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
```

But d3-format is much more than an alias for [number.toFixed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed)! A few more examples:

js

```
d3.format(".0%")(0.123) // rounded percentage, "12%"
```

js

```
d3.format("($.2f")(-3.5) // localized fixed-point currency, "(£3.50)"
```

js

```
d3.format("+20")(42) // space-filled and signed, "                 +42"
```

js

```
d3.format(".^20")(42) // dot-filled and centered, ".........42........."
```

js

```
d3.format(".2s")(42e6) // SI-prefix with two significant digits, "42M"
```

js

```
d3.format("#x")(48879) // prefixed lowercase hexadecimal, "0xbeef"
```

js

```
d3.format(",.2r")(4223) // grouped thousands with two significant digits, "4,200"
```

See [_locale_.format](https://d3js.org/d3-format#locale_format) for a detailed specification, and try running [d3.formatSpecifier](https://d3js.org/d3-format#formatSpecifier) on the above formats to decode their meaning.

Also see [_number_.toLocaleString](https://observablehq.com/@mbostock/number-formatting).

## format( _specifier_) [​](https://d3js.org/d3-format\#format)

js

```
const f = d3.format(".2f");
```

[Source](https://github.com/d3/d3-format/blob/main/src/defaultLocale.js) · An alias for [_locale_.format](https://d3js.org/d3-format#locale_format) on the [default locale](https://d3js.org/d3-format#formatDefaultLocale).

## formatPrefix( _specifier_, _value_) [​](https://d3js.org/d3-format\#formatPrefix)

js

```
const f = d3.formatPrefix(",.0", 1e-6);
```

[Source](https://github.com/d3/d3-format/blob/main/src/defaultLocale.js) · An alias for [_locale_.formatPrefix](https://d3js.org/d3-format#locale_formatPrefix) on the [default locale](https://d3js.org/d3-format#formatDefaultLocale).

## formatLocale( _definition_) [​](https://d3js.org/d3-format\#formatLocale)

js

```
const enUs = d3.formatLocale({
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});
```

[Source](https://github.com/d3/d3-format/blob/main/src/locale.js) · Returns a _locale_ object for the specified _definition_ with [_locale_.format](https://d3js.org/d3-format#locale_format) and [_locale_.formatPrefix](https://d3js.org/d3-format#locale_formatPrefix) methods. The _definition_ must include the following properties:

- `decimal` \- the decimal point (e.g., `"."`).
- `thousands` \- the group separator (e.g., `","`).
- `grouping` \- the array of group sizes (e.g., `[3]`), cycled as needed.
- `currency` \- the currency prefix and suffix (e.g., `["$", ""]`).
- `numerals` \- optional; an array of ten strings to replace the numerals 0-9.
- `percent` \- optional; the percent sign (defaults to `"%"`).
- `minus` \- optional; the minus sign (defaults to `"−"`).
- `nan` \- optional; the not-a-number value (defaults `"NaN"`).

Note that the _thousands_ property is a misnomer, as the grouping definition allows groups other than thousands.

## formatDefaultLocale( _definition_) [​](https://d3js.org/d3-format\#formatDefaultLocale)

js

```
const enUs = d3.formatDefaultLocale({
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});
```

[Source](https://github.com/d3/d3-format/blob/main/src/defaultLocale.js) · Equivalent to [d3.formatLocale](https://d3js.org/d3-format#formatLocale), except it also redefines [d3.format](https://d3js.org/d3-format#format) and [d3.formatPrefix](https://d3js.org/d3-format#formatPrefix) to the new locale’s [_locale_.format](https://d3js.org/d3-format#locale_format) and [_locale_.formatPrefix](https://d3js.org/d3-format#locale_formatPrefix). If you do not set a default locale, it defaults to [U.S. English](https://github.com/d3/d3-format/blob/main/locale/en-US.json).

## _locale_.format( _specifier_) [​](https://d3js.org/d3-format\#locale_format)

js

```
const f = d3.format(".2f");
```

[Source](https://github.com/d3/d3-format/blob/main/src/locale.js) · Returns a new format function for the given string _specifier_. The returned function takes a number as the only argument, and returns a string representing the formatted number. The general form of a specifier is:

```
[​[fill]align][sign][symbol][0][width][,][.precision][~][type]
```

The _fill_ can be any character. The presence of a fill character is signaled by the _align_ character following it, which must be one of the following:

- `>` \- Forces the field to be right-aligned within the available space. (Default behavior).
- `<` \- Forces the field to be left-aligned within the available space.
- `^` \- Forces the field to be centered within the available space.
- `=` \- like `>`, but with any sign and symbol to the left of any padding.

The _sign_ can be:

- `-` \- nothing for zero or positive and a minus sign for negative. (Default behavior.)
- `+` \- a plus sign for zero or positive and a minus sign for negative.
- `(` \- nothing for zero or positive and parentheses for negative.
- ` ` (space) - a space for zero or positive and a minus sign for negative.

The _symbol_ can be:

- `$` \- apply currency symbols per the locale definition.
- `#` \- for binary, octal, or hexadecimal notation, prefix by `0b`, `0o`, or `0x`, respectively.

The _zero_ ( `0`) option enables zero-padding; this implicitly sets _fill_ to `0` and _align_ to `=`. The _width_ defines the minimum field width; if not specified, then the width will be determined by the content. The _comma_ ( `,`) option enables the use of a group separator, such as a comma for thousands.

Depending on the _type_, the _precision_ either indicates the number of digits that follow the decimal point (types `f` and `%`), or the number of significant digits (types `​`, `e`, `g`, `r`, `s` and `p`). If the precision is not specified, it defaults to 6 for all types except `​` (none), which defaults to 12. Precision is ignored for integer formats (types `b`, `o`, `d`, `x`, and `X`) and character data (type `c`). See [precisionFixed](https://d3js.org/d3-format#precisionFixed) and [precisionRound](https://d3js.org/d3-format#precisionRound) for help picking an appropriate precision.

The `~` option trims insignificant trailing zeros across all format types. This is most commonly used in conjunction with types `r`, `e`, `s` and `%`. For example:

js

```
d3.format("s")(1500) // "1.50000k"
```

js

```
d3.format("~s")(1500) // "1.5k"
```

The available _type_ values are:

- `e` \- exponent notation.
- `f` \- fixed point notation.
- `g` \- either decimal or exponent notation, rounded to significant digits.
- `r` \- decimal notation, rounded to significant digits.
- `s` \- decimal notation with an [SI prefix](https://d3js.org/d3-format#locale_formatPrefix), rounded to significant digits.
- `%` \- multiply by 100, and then decimal notation with a percent sign.
- `p` \- multiply by 100, round to significant digits, and then decimal notation with a percent sign.
- `b` \- binary notation, rounded to integer.
- `o` \- octal notation, rounded to integer.
- `d` \- decimal notation, rounded to integer.
- `x` \- hexadecimal notation, using lower-case letters, rounded to integer.
- `X` \- hexadecimal notation, using upper-case letters, rounded to integer.
- `c` \- character data, for a string of text.

The type `​` (none) is also supported as shorthand for `~g` (with a default precision of 12 instead of 6), and the type `n` is shorthand for `,g`. For the `g`, `n` and `​` (none) types, decimal notation is used if the resulting string would have _precision_ or fewer digits; otherwise, exponent notation is used. For example:

js

```
d3.format(".2")(42) // "42"
```

js

```
d3.format(".2")(4.2) // "4.2"
```

js

```
d3.format(".1")(42) // "4e+1"
```

js

```
d3.format(".1")(4.2) // "4"
```

## _locale_.formatPrefix( _specifier_, _value_) [​](https://d3js.org/d3-format\#locale_formatPrefix)

js

```
const f = d3.formatPrefix(",.0", 1e-6);
```

[Source](https://github.com/d3/d3-format/blob/main/src/locale.js) · Equivalent to [_locale_.format](https://d3js.org/d3-format#locale_format), except the returned function will convert values to the units of the appropriate [SI prefix](https://en.wikipedia.org/wiki/Metric_prefix#List_of_SI_prefixes) for the specified numeric reference _value_ before formatting in fixed point notation. The following prefixes are supported:

- `y` \- yocto, 10⁻²⁴
- `z` \- zepto, 10⁻²¹
- `a` \- atto, 10⁻¹⁸
- `f` \- femto, 10⁻¹⁵
- `p` \- pico, 10⁻¹²
- `n` \- nano, 10⁻⁹
- `µ` \- micro, 10⁻⁶
- `m` \- milli, 10⁻³
- `​` (none) - 10⁰
- `k` \- kilo, 10³
- `M` \- mega, 10⁶
- `G` \- giga, 10⁹
- `T` \- tera, 10¹²
- `P` \- peta, 10¹⁵
- `E` \- exa, 10¹⁸
- `Z` \- zetta, 10²¹
- `Y` \- yotta, 10²⁴

Unlike [_locale_.format](https://d3js.org/d3-format#locale_format) with the `s` format type, this method returns a formatter with a consistent SI prefix, rather than computing the prefix dynamically for each number. In addition, the _precision_ for the given _specifier_ represents the number of digits past the decimal point (as with `f` fixed point notation), not the number of significant digits. For example:

js

```
const f = d3.formatPrefix(",.0", 1e-6);
f(0.00042); // "420µ"
f(0.0042); // "4,200µ"
```

This method is useful when formatting multiple numbers in the same units for easy comparison. See [precisionPrefix](https://d3js.org/d3-format#precisionPrefix) for help picking an appropriate precision.

## formatSpecifier( _specifier_) [​](https://d3js.org/d3-format\#formatSpecifier)

js

```
d3.formatSpecifier(".1f")
```

[Source](https://github.com/d3/d3-format/blob/main/src/formatSpecifier.js) · Parses the specified _specifier_, returning an object with exposed fields that correspond to the [format specification mini-language](https://d3js.org/d3-format#locale_format) and a toString method that reconstructs the specifier. For example, `formatSpecifier("s")` returns:

js

```
FormatSpecifier {
  "fill": " ",
  "align": ">",
  "sign": "-",
  "symbol": "",
  "zero": false,
  "width": undefined,
  "comma": false,
  "precision": undefined,
  "trim": false,
  "type": "s"
}
```

This method is useful for understanding how format specifiers are parsed and for deriving new specifiers. For example, you might compute an appropriate precision based on the numbers you want to format using [precisionFixed](https://d3js.org/d3-format#precisionFixed) and then create a new format:

js

```
const s = d3.formatSpecifier("f");
s.precision = d3.precisionFixed(0.01);
const f = d3.format(s);
f(42); // "42.00";
```

## new d3.FormatSpecifier( _specifier_) [​](https://d3js.org/d3-format\#FormatSpecifier)

js

```
new d3.FormatSpecifier({type: "f", precision: 1})
```

[Source](https://github.com/d3/d3-format/blob/main/src/formatSpecifier.js) · Given the specified _specifier_ object, returning an object with exposed fields that correspond to the [format specification mini-language](https://d3js.org/d3-format#locale_format) and a toString method that reconstructs the specifier. For example, `new FormatSpecifier({type: "s"})` returns:

js

```
FormatSpecifier {
  "fill": " ",
  "align": ">",
  "sign": "-",
  "symbol": "",
  "zero": false,
  "width": undefined,
  "comma": false,
  "precision": undefined,
  "trim": false,
  "type": "s"
}
```

## precisionFixed( _step_) [​](https://d3js.org/d3-format\#precisionFixed)

js

```
d3.precisionFixed(0.01) // 2
```

[Source](https://github.com/d3/d3-format/blob/main/src/precisionFixed.js) · Returns a suggested decimal precision for fixed point notation given the specified numeric _step_ value. The _step_ represents the minimum absolute difference between values that will be formatted. (This assumes that the values to be formatted are also multiples of _step_.) For example, given the numbers 1, 1.5, and 2, the _step_ should be 0.5 and the suggested precision is 1:

js

```
const p = d3.precisionFixed(0.5);
const f = d3.format("." + p + "f");
f(1);   // "1.0"
f(1.5); // "1.5"
f(2);   // "2.0"
```

Whereas for the numbers 1, 2 and 3, the _step_ should be 1 and the suggested precision is 0:

js

```
const p = d3.precisionFixed(1);
const f = d3.format("." + p + "f");
f(1); // "1"
f(2); // "2"
f(3); // "3"
```

Note: for the `%` format type, subtract two:

js

```
const p = Math.max(0, d3.precisionFixed(0.05) - 2);
const f = d3.format("." + p + "%");
f(0.45); // "45%"
f(0.50); // "50%"
f(0.55); // "55%"
```

## precisionPrefix( _step_, _value_) [​](https://d3js.org/d3-format\#precisionPrefix)

js

```
d3.precisionPrefix(1e5, 1.3e6) // 1
```

[Source](https://github.com/d3/d3-format/blob/main/src/precisionPrefix.js) · Returns a suggested decimal precision for use with [_locale_.formatPrefix](https://d3js.org/d3-format#locale_formatPrefix) given the specified numeric _step_ and reference _value_. The _step_ represents the minimum absolute difference between values that will be formatted, and _value_ determines which SI prefix will be used. (This assumes that the values to be formatted are also multiples of _step_.) For example, given the numbers 1.1e6, 1.2e6, and 1.3e6, the _step_ should be 1e5, the _value_ could be 1.3e6, and the suggested precision is 1:

js

```
const p = d3.precisionPrefix(1e5, 1.3e6);
const f = d3.formatPrefix("." + p, 1.3e6);
f(1.1e6); // "1.1M"
f(1.2e6); // "1.2M"
f(1.3e6); // "1.3M"
```

## precisionRound( _step_, _max_) [​](https://d3js.org/d3-format\#precisionRound)

js

```
d3.precisionRound(0.01, 1.01) // 3
```

[Source](https://github.com/d3/d3-format/blob/main/src/precisionRound.js) · Returns a suggested decimal precision for format types that round to significant digits given the specified numeric _step_ and _max_ values. The _step_ represents the minimum absolute difference between values that will be formatted, and the _max_ represents the largest absolute value that will be formatted. (This assumes that the values to be formatted are also multiples of _step_.) For example, given the numbers 0.99, 1.0, and 1.01, the _step_ should be 0.01, the _max_ should be 1.01, and the suggested precision is 3:

js

```
const p = d3.precisionRound(0.01, 1.01);
const f = d3.format("." + p + "r");
f(0.99); // "0.990"
f(1.0);  // "1.00"
f(1.01); // "1.01"
```

Whereas for the numbers 0.9, 1.0, and 1.1, the _step_ should be 0.1, the _max_ should be 1.1, and the suggested precision is 2:

js

```
const p = d3.precisionRound(0.1, 1.1);
const f = d3.format("." + p + "r");
f(0.9); // "0.90"
f(1.0); // "1.0"
f(1.1); // "1.1"
```

Note: for the `e` format type, subtract one:

js

```
const p = Math.max(0, d3.precisionRound(0.01, 1.01) - 1);
const f = d3.format("." + p + "e");
f(0.01); // "1.00e-2"
f(1.01); // "1.01e+0"
```

