NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
npm, #2486 most downloaded on npm
Data-Driven Documents
Latest stable
7.9.2
Last release 14 days ago
03 Nov 2026
Ships unpredictably
gaps range from 9 days to 2.6 years
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
15 years old
275 releases · first in 2011
Drag across the ruler to compare, or tap a release to open it.
Fix achromatic representation of black and white in d3.hcl.
Fix d3.stackDivergingOffset when there is only one series.
Your coding agent can read these notes before it upgrades. Set up the MCP server →
Fix bug when initializing nodes with fixed positions in force simulations.
Fix corruption when *quadtree*.cover is coincident with the current extent.
Add d3.autoType for automatic type inference when parsing!
Fix d3.timeMinute and d3.timeHour for historical times.
Fix rendering glitch with *arc*.cornerRadius.
Add *iterations* argument to *simulation*.tick. Thanks, @vasturiano!
Fix upper histogram bin threshold in some cases.
Use currentColor instead of black for axes.
Fix treatment of degenerate domains in d3.scaleSequential.
* Add d3.interpolateSinebow.
Add ~ option to d3.format to trim insignificant zeros. Thanks, @vasturiano!
~ option to d3.format to trim insignificant zeros. Thanks, @vasturiano!* Add *color*.hex. * Add d3.piecewise.
Switch from D65 to D50 for Lab and HCL color spaces. Thanks, @danburzo!
Replaced by 5.1.0.
Replaced by 5.1.0.
Fix occasional overlap and hang in d3.packSiblings. Thanks, @robinhouston!
Remove d3-request; add d3-fetch.
D3 now includes new categorical color schemes from ColorBrewer, along with ColorBrewer’s excellent diverging, sequential single-hue and sequential multi-hue color schemes. The twenty-color schemes were removed because their grouped design often falsely implied non-existent relationships in the data: a shared hue can imply that the encoded data are part of a group (a super-category), while the relative lightness can falsely imply order.
For more on what’s new, read CHANGES.
D3 5.0 introduces only a few non-backwards-compatible changes.
D3 now uses Promises instead of asynchronous callbacks to load data. Promises simplify the structure of asynchronous code, especially in modern browsers that support async and await. (See this introduction to promises on Observable.) For example, to load a CSV file in v4, you might say:
d3.csv("file.csv", function(error, data) {
if (error) throw error;
console.log(data);
});
In v5, using promises:
d3.csv("file.csv").then(function(data) {
console.log(data);
});
Note that you don’t need to rethrow the error—the promise will reject automatically, and you can promise.catch if desired. Using await, the code is even simpler:
const data = await d3.csv("file.csv");
console.log(data);
With the adoption of promises, D3 now uses the Fetch API instead of XMLHttpRequest: the d3-request module has been replaced by d3-fetch. Fetch supports many powerful new features, such as streaming responses. D3 5.0 also deprecates and removes the d3-queue module. Use Promise.all to run a batch of asynchronous tasks in parallel, or a helper library such as p-queue to control concurrency.
D3 no longer provides the d3.schemeCategory20* categorical color schemes. These twenty-color schemes were flawed because their grouped design could falsely imply relationships in the data: a shared hue can imply that the encoded data are part of a group (a super-category), while relative lightness can imply order. Instead, D3 now includes d3-scale-chromatic, which implements excellent schemes from ColorBrewer, including categorical, diverging, sequential single-hue and sequential multi-hue schemes. These schemes are available in both discrete and continuous variants.
D3 now provides implementations of marching squares and density estimation via d3-contour! There are two new d3-selection methods: selection.clone for inserting clones of the selected nodes, and d3.create for creating detached elements. Geographic projections now support projection.angle, which has enabled several fantastic new polyhedral projections by Philippe Rivière.
Lastly, D3’s package.json no longer pins exact versions of the dependent D3 modules. This fixes an issue with duplicate installs of D3 modules.
Nothing published for this version
Nothing published for this version
Nothing published for this version
Moved to https://github.com/d3/d3/releases/tag/v5.0.0
Moved to https://github.com/d3/d3/releases/tag/v5.0.0
Fix d3.format’s SI format for locales with currency suffixes.
Pin to earlier version of UglifyJS to fix minified bundle.
Point unpkg and jsDelivr to the minified bundle.
Add f, Q, s, u and V time format specifiers. Thanks, @BrianMitchL @krukon!
f, Q, s, u and V time format specifiers. Thanks, @BrianMitchL @krukon!Add d3.forceRadial. Thanks, @nbremer!
Fix d3.timer sleeping for too long when timer invocation is expensive.
Fix DSV parsing when the last field is empty (e.g., foo,bar,).
foo,bar,).browser field in package.json with unpkg and jsdeliver. (#3138)prepublish script with prepublishOnly.Add d3.areaRadial; deprecate d3.radialArea.
Fix d3.linkRadial to use radians rather than degrees.
Change *selection*.style to return the inline style, if present.
Fix d3.ticks to always return the most-precise representable values in IEEE 754!
Fix primary touch location on secondary touchend when zooming.
Fix the Mercator projection’s built-in clipping when *projection*.rotate is used.
Fix string coercion in *transition*.style and *transition*.attr. Thanks, @sghall!
Fix the Mercator projection’s built-in clipping when _projection_.center is used.
Allow d3.pairs to take an optional reducer.
Fix d3.geoBounds for certain line geometries.
Nothing published for this version
Fix overlapping circles in d3.pack and d3.packSiblings.
Fix calculation of clock skew when page is backgrounded before timers are scheduled.
- Fix d3.event export on Node.
Fix d3.interpolateRgb.gamma’s opacity interpolation.
Fix handling of zoom gestures that start with multiple touches.
Add _identity_.reflectX and _identity_.reflectY to d3.geoIdentity.
Deprecate d3.geoClipExtent; use d3.geoIdentity’s clipExtent instead.
Fix reporting of _interrupt_ transition events.
Fix bug where calling _collide_.radius had no effect.
Fix hang in _interval_.every(…).range given invalid dates.
Fix cache invalidation bug in d3.geoAlbersUsa.
Fix a crash if brush selection is cleared via _brush_.move during a gesture.
Chained transitions no longer sometimes interrupt their preceding transition.
Fix d3.geoStereographic’s invert.
All modules now expose a module entry point (rollup/rollup-plugin-node-resolve#48).
module entry point (rollup/rollup-plugin-node-resolve#48).Add _projection_.fitExtent and _projection_.fitSize. Thanks, @veltman!
Deprecate the optional _step_ argument to _time_.ticks; use _interval_.every instead.
Export raw geographic projections.
D3 is now modular, composed of many small libraries that you can also use independently. Each library has its own repo and release cycle for faster de
D3 is now modular, composed of many small libraries that you can also use independently. Each library has its own repo and release cycle for faster development. The modular approach also improves the process for custom bundles and plugins.
There are a lot of improvements in 4.0: there were about as many commits in 4.0 as in all prior versions of D3. Some changes make D3 easier to learn and use, such as immutable selections. But there are lots of new features, too! These are covered in detail in the release notes; here are a few highlights.
D3 4.0 is modular. Instead of one library, D3 is now many small libraries that are designed to work together. You can pick and choose which parts to use as you see fit. Each library is maintained in its own repository, allowing decentralized ownership and independent release cycles. The default bundle combines about thirty of these microlibraries.
<script src="https://d3js.org/d3.v4.js"></script>
As before, you can load optional plugins on top of the default bundle, such as ColorBrewer scales:
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v0.3.js"></script>
You are not required to use the default bundle! If you’re just using d3-selection, use it as a standalone library. Like the default bundle, you can load D3 microlibraries using vanilla script tags or RequireJS (great for HTTP/2!):
<script src="https://d3js.org/d3-selection.v1.js"></script>
You can also cat D3 microlibraries into a custom bundle, or use tools such as Webpack and Rollup to create optimized bundles. Custom bundles are great for applications that use a subset of D3’s features; for example, a React chart library might use D3 for scales and shapes, and React to manipulate the DOM. The D3 microlibraries are written as ES6 modules, and Rollup lets you pick at the symbol level to produce smaller bundles.
Small files are nice, but modularity is also about making D3 more fun. Microlibraries are easier to understand, develop and test. They make it easier for new people to get involved and contribute. They reduce the distinction between a “core module” and a “plugin”, and increase the pace of development in D3 features.
If you don’t care about modularity, you can mostly ignore this change and keep using the default bundle. However, there is one unavoidable consequence of adopting ES6 modules: every symbol in D3 4.0 now shares a flat namespace rather than the nested one of D3 3.x. For example, d3.scale.linear is now d3.scaleLinear, and d3.layout.treemap is now d3.treemap. The adoption of ES6 modules also means that D3 is now written exclusively in strict mode and has better readability. And there have been many other significant improvements to D3’s features! (Nearly all of the code from D3 3.x has been rewritten.) These changes are covered below.
The default UMD bundle is now anonymous. No d3 global is exported if AMD or CommonJS is detected. In a vanilla environment, the D3 microlibraries share the d3 global, even if you load them independently; thus, code you write is the same whether or not you use the default bundle. (See Let’s Make a (D3) Plugin for more.) The generated bundle is no longer stored in the Git repository; Bower has been repointed to d3-bower, and you can find the generated files on npm or attached to the latest release. The non-minified default bundle is no longer mangled, making it more readable and preserving inline comments.
To the consternation of some users, 3.x employed Unicode variable names such as λ, φ, τ and π for a concise representation of mathematical operations. A downside of this approach was that a SyntaxError would occur if you loaded the non-minified D3 using ISO-8859-1 instead of UTF-8. 3.x also used Unicode string literals, such as the SI-prefix µ for 1e-6. 4.0 uses only ASCII variable names and ASCII string literals (see rollup-plugin-ascii), avoiding encoding problems.
The new d3.scan method performs a linear scan of an array, returning the index of the least element according to the specified comparator. This is similar to d3.min and d3.max, except you can use it to find the position of an extreme element, rather than just calculate an extreme value.
var data = [
{name: "Alice", value: 2},
{name: "Bob", value: 3},
{name: "Carol", value: 1},
{name: "Dwayne", value: 5}
];
var i = d3.scan(data, function(a, b) { return a.value - b.value; }); // 2
data[i]; // {name: "Carol", value: 1}
The new d3.ticks and d3.tickStep methods are useful for generating human-readable numeric ticks. These methods are a low-level alternative to continuous.ticks from d3-scale. The new implementation is also more accurate, returning the optimal number of ticks as measured by relative error.
var ticks = d3.ticks(0, 10, 5); // [0, 2, 4, 6, 8, 10]
The d3.range method no longer makes an elaborate attempt to avoid floating-point error when step is not an integer. The returned values are strictly defined as start + i * step, where i is an integer. (Learn more about floating point math.) d3.range returns the empty array for infinite ranges, rather than throwing an error.
The method signature for optional accessors has been changed to be more consistent with array methods such as array.forEach: the accessor is passed the current element (d), the index (i), and the array (data), with this as undefined. This affects d3.min, d3.max, d3.extent, d3.sum, d3.mean, d3.median, d3.quantile, d3.variance and d3.deviation. The d3.quantile method previously did not take an accessor. Some methods with optional arguments now treat those arguments as missing if they are null or undefined, rather than strictly checking arguments.length.
The new d3.histogram API replaces d3.layout.histogram. Rather than exposing bin.x and bin.dx on each returned bin, the histogram exposes bin.x0 and bin.x1, guaranteeing that bin.x0 is exactly equal to bin.x1 on the preceding bin. The “frequency” and “probability” modes are no longer supported; each bin is simply an array of elements from the input data, so bin.length is equal to D3 3.x’s bin.y in frequency mode. To compute a probability distribution, divide the number of elements in each bin by the total number of elements.
The histogram.range method has been renamed histogram.domain for consistency with scales. The histogram.bins method has been renamed histogram.thresholds, and no longer accepts an upper value: n thresholds will produce n + 1 bins. If you specify a desired number of bins rather than thresholds, d3.histogram now uses d3.ticks to compute nice bin thresholds. In addition to the default Sturges’ formula, D3 now implements the Freedman-Diaconis rule and Scott’s normal reference rule.
To render axes properly in D3 3.x, you needed to style them:
<style>
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.axis text {
font: 10px sans-serif;
}
</style>
<script>
d3.select(".axis")
.call(d3.svg.axis()
.scale(x)
.orient("bottom"));
</script>
If you didn’t, you saw this:
<img src="https://raw.githubusercontent.com/d3/d3/master/img/axis-v3.png" width="100%" height="105">
D3 4.0 provides default styles and shorter syntax. In place of d3.svg.axis and axis.orient, D3 4.0 now provides four constructors for each orientation: d3.axisTop, d3.axisRight, d3.axisBottom, d3.axisLeft. These constructors accept a scale, so you can reduce all of the above to:
<script>
d3.select(".axis")
.call(d3.axisBottom(x));
</script>
And get this:
<img src="https://raw.githubusercontent.com/d3/d3/master/img/axis-v4.png" width="100%" height="105">
As before, you can customize the axis appearance either by applying stylesheets or by modifying the axis elements. The default appearance has been changed slightly to offset the axis by a half-pixel; this fixes a crisp-edges rendering issue on Safari where the axis would be drawn two-pixels thick.
There’s now an axis.tickArguments method, as an alternative to axis.ticks that also allows the axis tick arguments to be inspected. The axis.tickSize method has been changed to only allow a single argument when setting the tick size. The axis.innerTickSize and axis.outerTickSize methods have been renamed axis.tickSizeInner and axis.tickSizeOuter, respectively.
Replacing d3.svg.brush, there are now three classes of brush for brushing along the x-dimension, the y-dimension, or both: d3.brushX, d3.brushY, d3.brush. Brushes are no longer dependent on scales; instead, each brush defines a selection in screen coordinates. This selection can be inverted if you want to compute the corresponding data domain. And rather than rely on the scales’ ranges to determine the brushable area, there is now a brush.extent method for setting it. If you do not set the brush extent, it defaults to the full extent of the owner SVG element. The brush.clamp method has also been eliminated; brushing is always restricted to the brushable area defined by the brush extent.
Brushes no longer store the active brush selection (i.e., the highlighted region; the brush’s position) internally. The brush’s position is now stored on any elements to which the brush has been applied. The brush’s position is available as event.selection within a brush event or by calling d3.brushSelection on a given element. To move the brush programmatically, use brush.move with a given selection or transition; see the brush snapping example. The brush.event method has been removed.
Brush interaction has been improved. By default, brushes now ignore right-clicks intended for the context menu; you can change this behavior using brush.filter. Brushes also ignore emulated mouse events on iOS. Holding down SHIFT (⇧) while brushing locks the x- or y-position of the brush. Holding down META (⌘) while clicking and dragging starts a new selection, rather than translating the existing selection.
The default appearance of the brush has also been improved and slightly simplified. Previously it was necessary to apply styles to the brush to give it a reasonable appearance, such as:
.brush .extent {
stroke: #fff;
fill-opacity: .125;
shape-rendering: crispEdges;
}
These styles are now applied by default as attributes; if you want to customize the brush appearance, you can still apply external styles or modify the brush elements. (D3 4.0 features a similar improvement to axes.) A new brush.handleSize method lets you override the brush handle size; it defaults to six pixels.
The brush now consumes handled events, making it easier to combine with other interactive behaviors such as dragging and zooming. The brushstart and brushend events have been renamed to start and end, respectively. The brush event no longer reports a event.mode to distinguish between resizing and dragging the brush.
Pursuant to the great namespace flattening:
For consistency with arc.padAngle, chord.padding has also been renamed to ribbon.padAngle. A new ribbon.context method lets you render chord diagrams to Canvas! See also d3-path.
The d3.set constructor now accepts an existing set for making a copy. If you pass an array to d3.set, you can also pass a value accessor. This accessor takes the standard arguments: the current element (d), the index (i), and the array (data), with this undefined. For example:
var yields = [
{yield: 22.13333, variety: "Manchuria", year: 1932, site: "Grand Rapids"},
{yield: 26.76667, variety: "Peatland", year: 1932, site: "Grand Rapids"},
{yield: 28.10000, variety: "No. 462", year: 1931, site: "Duluth"},
{yield: 38.50000, variety: "Svansota", year: 1932, site: "Waseca"},
{yield: 40.46667, variety: "Svansota", year: 1931, site: "Crookston"},
{yield: 36.03333, variety: "Peatland", year: 1932, site: "Waseca"},
{yield: 34.46667, variety: "Wisconsin No. 38", year: 1931, site: "Grand Rapids"}
];
var sites = d3.set(yields, function(d) { return d.site; }); // Grand Rapids, Duluth, Waseca, Crookston
The d3.map constructor also follows the standard array accessor argument pattern.
The map.forEach and set.forEach methods have been renamed to map.each and set.each respectively. The order of arguments for map.each has also been changed to value, key and map, while the order of arguments for set.each is now value, value and set. This is closer to ES6 map.forEach and set.forEach. Also like ES6 Map and Set, map.set and set.add now return the current collection (rather than the added value) to facilitate method chaining. New map.clear and set.clear methods can be used to empty collections.
The nest.map method now always returns a d3.map instance. For a plain object, use nest.object instead. When used in conjunction with nest.rollup, nest.entries now returns {key, value} objects for the leaf entries, instead of {key, values}. This makes nest.rollup easier to use in conjunction with hierarchies, as in this Nest Treemap example.
All colors now have opacity exposed as color.opacity, which is a number in [0, 1]. You can pass an optional opacity argument to the color space constructors d3.rgb, d3.hsl, d3.lab, d3.hcl or d3.cubehelix.
You can now parse rgba(…) and hsla(…) CSS color specifiers or the string “transparent” using d3.color. The “transparent” color is defined as an RGB color with zero opacity and undefined red, green and blue channels; this differs slightly from CSS which defines it as transparent black, but is useful for simplifying color interpolation logic where either the starting or ending color has undefined channels. The color.toString method now likewise returns an rgb(…) or rgba(…) string with integer channel values, not the hexadecimal RGB format, consistent with CSS computed values. This improves performance by short-circuiting transitions when the element’s starting style matches its ending style.
The new d3.color method is the primary method for parsing colors: it returns a d3.color instance in the appropriate color space, or null if the CSS color specifier is invalid. For example:
var red = d3.color("hsl(0, 80%, 50%)"); // {h: 0, l: 0.5, s: 0.8, opacity: 1}
The parsing implementation is now more robust. For example, you can no longer mix integers and percentages in rgb(…), and it correctly handles whitespace, decimal points, number signs, and other edge cases. The color space constructors d3.rgb, d3.hsl, d3.lab, d3.hcl and d3.cubehelix now always return a copy of the input color, converted to the corresponding color space. While color.rgb remains, rgb.hsl has been removed; use d3.hsl to convert a color to the RGB color space.
The RGB color space no longer greedily quantizes and clamps channel values when creating colors, improving accuracy in color space conversion. Quantization and clamping now occurs in color.toString when formatting a color for display. You can use the new color.displayable to test whether a color is out-of-gamut.
The rgb.brighter method no longer special-cases black. This is a multiplicative operator, defining a new color r′, g′, b′ where r′ = r × pow(0.7, k), g′ = g × pow(0.7, k) and b′ = b × pow(0.7, k); a brighter black is still black.
There’s a new d3.cubehelix color space, generalizing Dave Green’s color scheme! (See also d3.interpolateCubehelixDefault from d3-scale.) You can continue to define your own custom color spaces, too; see d3-hsv for an example.
Rather than decorating the dispatch object with each event type, the dispatch object now exposes generic dispatch.call and dispatch.apply methods which take the type string as the first argument. For example, in D3 3.x, you might say:
dispatcher.foo.call(that, "Hello, Foo!");
To dispatch a foo event in D3 4.0, you’d say:
dispatcher.call("foo", that, "Hello, Foo!");
The dispatch.on method now accepts multiple typenames, allowing you to add or remove listeners for multiple events simultaneously. For example, to send both foo and bar events to the same listener:
dispatcher.on("foo bar", function(message) {
console.log(message);
});
This matches the new behavior of selection.on in d3-selection. The dispatch.on method now validates that the specifier listener is a function, rather than throwing an error in the future.
The new implementation d3.dispatch is faster, using fewer closures to improve performance. There’s also a new dispatch.copy method for making a copy of a dispatcher; this is used by d3-transition to improve the performance of transitions in the common case where all elements in a transition have the same transition event listeners.
The drag behavior d3.behavior.drag has been renamed to d3.drag. The drag.origin method has been replaced by drag.subject, which allows you to define the thing being dragged at the start of a drag gesture. This is particularly useful with Canvas, where draggable objects typically share a Canvas element (as opposed to SVG, where draggable objects typically have distinct DOM elements); see the circle dragging example.
A new drag.container method lets you override the parent element that defines the drag gesture coordinate system. This defaults to the parent node of the element to which the drag behavior was applied. For dragging on Canvas elements, you probably want to use the Canvas element as the container.
Drag events now expose an event.on method for registering temporary listeners for duration of the current drag gesture; these listeners can capture state for the current gesture, such as the thing being dragged. A new event.active property lets you detect whether multiple (multitouch) drag gestures are active concurrently. The dragstart and dragend events have been renamed to start and end. By default, drag behaviors now ignore right-clicks intended for the context menu; use drag.filter to control which events are ignored. The drag behavior also ignores emulated mouse events on iOS. The drag behavior now consumes handled events, making it easier to combine with other interactive behaviors such as zooming.
The new d3.dragEnable and d3.dragDisable methods provide a low-level API for implementing drag gestures across browsers and devices. These methods are also used by other D3 components, such as the brush.
Pursuant to the great namespace flattening, various CSV and TSV methods have new names:
The d3.csv and d3.tsv methods for loading files of the corresponding formats have not been renamed, however! Those are defined in d3-request.There’s no longer a d3.dsv method, which served the triple purpose of defining a DSV formatter, a DSV parser and a DSV requestor; instead, there’s just d3.dsvFormat which you can use to define a DSV formatter and parser. You can use request.response to make a request and then parse the response body, or just use d3.text.
The dsv.parse method now exposes the column names and their input order as data.columns. For example:
d3.csv("cars.csv", function(error, data) {
if (error) throw error;
console.log(data.columns); // ["Year", "Make", "Model", "Length"]
});
You can likewise pass an optional array of column names to dsv.format to format only a subset of columns, or to specify the column order explicitly:
var string = d3.csvFormat(data, ["Year", "Model", "Length"]);
The parser is a bit faster and the formatter is a bit more robust: inputs are coerced to strings before formatting, fixing an obscure crash, and deprecated support for falling back to dsv.formatRows when the input data is an array of arrays has been removed.
D3 3.x used strings, such as “cubic-in-out”, to identify easing methods; these strings could be passed to d3.ease or transition.ease. D3 4.0 uses symbols instead, such as d3.easeCubicInOut. Symbols are simpler and cleaner. They work well with Rollup to produce smaller custom bundles. You can still define your own custom easing function, too, if desired. Here’s the full list of equivalents:
¹ The -in, -out and -in-out variants of linear easing are identical, so there’s just d3.easeLinear. <br>² Elastic and bounce easing were inadvertently reversed in 3.x, so 4.0 eliminates -out-in easing!
For convenience, there are also default aliases for each easing method. For example, d3.easeCubic is an alias for d3.easeCubicInOut. Most default to -in-out; the exceptions are d3.easeBounce and d3.easeElastic, which default to -out.
Rather than pass optional arguments to d3.ease or transition.ease, parameterizable easing functions now have named parameters: poly.exponent, elastic.amplitude, elastic.period and back.overshoot. For example, in D3 3.x you might say:
var e = d3.ease("elastic-out-in", 1.2);
The equivalent in D3 4.0 is:
var e = d3.easeElastic.amplitude(1.2);
Many of the easing functions have been optimized for performance and accuracy. Several bugs have been fixed, as well, such as the interpretation of the overshoot parameter for back easing, and the period parameter for elastic easing. Also, d3-transition now explicitly guarantees that the last tick of the transition happens at exactly t = 1, avoiding floating point errors in some easing functions.
There’s now a nice visual reference and an animated reference to the new easing functions, too!
The force layout d3.layout.force has been renamed to d3.forceSimulation. The force simulation now uses velocity Verlet integration rather than position Verlet, tracking the nodes’ positions (node.x, node.y) and velocities (node.vx, node.vy) rather than their previous positions (node.px, node.py).
Rather than hard-coding a set of built-in forces, the force simulation is now extensible: you specify which forces you want! The approach affords greater flexibility through composition. The new forces are more flexible, too: force parameters can typically be configured per-node or per-link. There are separate positioning forces for x and y that replace force.gravity; x.x and y.y replace force.size. The new link force replaces force.linkStrength and employs better default heuristics to improve stability. The new many-body force replaces force.charge and supports a new minimum-distance parameter and performance improvements thanks to 4.0’s new quadtrees. There are also brand-new forces for centering nodes and collision resolution.
The new forces and simulation have been carefully crafted to avoid nondeterminism. Rather than initializing nodes randomly, if the nodes do not have preset positions, they are placed in a phyllotaxis pattern:
<img alt="Phyllotaxis" src="https://raw.githubusercontent.com/d3/d3-force/master/img/phyllotaxis.png" width="420" height="219">
Random jitter is still needed to resolve link, collision and many-body forces if there are coincident nodes, but at least in the common case, the force simulation (and the resulting force-directed graph layout) is now consistent across browsers and reloads. D3 no longer plays dice!
The force simulation has several new methods for greater control over heating, such as simulation.alphaMin and simulation.alphaDecay, and the internal timer. Calling simulation.alpha now has no effect on the internal timer, which is controlled independently via simulation.stop and simulation.restart. The force layout’s internal timer now starts automatically on creation, removing force.start. As in 3.x, you can advance the simulation manually using simulation.tick. The force.friction parameter is replaced by simulation.velocityDecay. A new simulation.alphaTarget method allows you to set the desired alpha (temperature) of the simulation, such that the simulation can be smoothly reheated during interaction, and then smoothly cooled again. This improves the stability of the graph during interaction.
The force layout no longer depends on the drag behavior, though you can certainly create draggable force-directed graphs! Set node.fx and node.fy to fix a node’s position. As an alternative to a Voronoi SVG overlay, you can now use simulation.find to find the closest node to a pointer.
If a precision is not specified, the formatting behavior has changed: there is now a default precision of 6 for all directives except none, which defaults to 12. In 3.x, if you did not specify a precision, the number was formatted using its shortest unique representation (per number.toString); this could lead to unexpected digits due to floating point math. The new default precision in 4.0 produces more consistent results:
var f = d3.format("e");
f(42); // "4.200000e+1"
f(0.1 + 0.2); // "3.000000e-1"
To trim insignificant trailing zeroes, use the none directive, which is similar g. For example:
var f = d3.format(".3");
f(0.12345); // "0.123"
f(0.10000); // "0.1"
f(0.1 + 0.2); // "0.3"
Under the hood, number formatting has improved accuracy with very large and very small numbers by using number.toExponential rather than Math.log to extract the mantissa and exponent. Negative zero (-0, an IEEE 754 construct) and very small numbers that round to zero are now formatted as unsigned zero. The inherently unsafe d3.round method has been removed, along with d3.requote.
The d3.formatPrefix method has been changed. Rather than returning an SI-prefix string, it returns an SI-prefix format function for a given specifier and reference value. For example, to format thousands:
var f = d3.formatPrefix(",.0", 1e3);
f(1e3); // "1k"
f(1e4); // "10k"
f(1e5); // "100k"
f(1e6); // "1,000k"
Unlike the s format directive, d3.formatPrefix always employs the same SI-prefix, producing consistent results:
var f = d3.format(".0s");
f(1e3); // "1k"
f(1e4); // "10k"
f(1e5); // "100k"
f(1e6); // "1M"
The new ( sign option uses parentheses for negative values. This is particularly useful in conjunction with $. For example:
d3.format("+.0f")(-42); // "-42"
d3.format("(.0f")(-42); // "(42)"
d3.format("+$.0f")(-42); // "-$42"
d3.format("($.0f")(-42); // "($42)"
The new = align option places any sign and symbol to the left of any padding:
d3.format(">6d")(-42); // " -42"
d3.format("=6d")(-42); // "- 42"
d3.format(">(6d")(-42); // " (42)"
d3.format("=(6d")(-42); // "( 42)"
The b, o, d and x directives now round to the nearest integer, rather than returning the empty string for non-integers:
d3.format("b")(41.9); // "101010"
d3.format("o")(41.9); // "52"
d3.format("d")(41.9); // "42"
d3.format("x")(41.9); // "2a"
The c directive is now for character data (i.e., literal strings), not for character codes. The is useful if you just want to apply padding and alignment and don’t care about formatting numbers. For example, the infamous left-pad (as well as center- and right-pad!) can be conveniently implemented as:
d3.format(">10c")("foo"); // " foo"
d3.format("^10c")("foo"); // " foo "
d3.format("<10c")("foo"); // "foo "
There are several new methods for computing suggested decimal precisions; these are used by d3-scale for tick formatting, and are helpful for implementing custom number formats: d3.precisionFixed, d3.precisionPrefix and d3.precisionRound. There’s also a new d3.formatSpecifier method for parsing, validating and debugging format specifiers; it’s also good for deriving related format specifiers, such as when you want to substitute the precision automatically.
You can now set the default locale using d3.formatDefaultLocale! The locales are published as JSON to npm.
Pursuant to the great namespace flattening, various methods have new names:
Also renamed for consistency:
Projections now have more appropriate defaults. For example, d3.geoOrthographic has a 90° clip angle by default, showing only the front hemisphere, and d3.geoGnomonic has a default 60° clip angle. The default projection for d3.geoPath is now null rather than d3.geoAlbersUsa; a null projection is used with pre-projected geometry and is typically faster to render.
“Fallback projections”—when you pass a function rather than a projection to path.projection—are no longer supported. For geographic projections, use d3.geoProjection or d3.geoProjectionMutator to define a custom projection. For arbitrary geometry transformations, implement the stream interface; see also d3.geoTransform. The “raw” projections (e.g., d3.geo.equirectangular.raw) are no longer exported.
Pursuant to the great namespace flattening:
As an alternative to using JSON to represent hierarchical data (such as the “flare.json format” used by many D3 examples), the new d3.stratify operator simplifies the conversion of tabular data to hierarchical data! This is convenient if you already have data in a tabular format, such as the result of a SQL query or a CSV file:
name,parent
Eve,
Cain,Eve
Seth,Eve
Enos,Seth
Noam,Seth
Abel,Eve
Awan,Eve
Enoch,Awan
Azura,Eve
To convert this to a root node:
var root = d3.stratify()
.id(function(d) { return d.name; })
.parentId(function(d) { return d.parent; })
(nodes);
The resulting root can be passed to d3.tree to produce a tree diagram like this:
<img src="https://raw.githubusercontent.com/d3/d3/master/img/stratify.png" width="298" height="137">
Root nodes can also be created from JSON data using d3.hierarchy. The hierarchy layouts now take these root nodes as input rather than operating directly on JSON data, which helps to provide a cleaner separation between the input data and the computed layout. (For example, use node.copy to isolate layout changes.) It also simplifies the API: rather than each hierarchy layout needing to implement value and sorting accessors, there are now generic node.sum and node.sort methods that work with any hierarchy layout.
The new d3.hierarchy API also provides a richer set of methods for manipulating hierarchical data. For example, to generate an array of all nodes in topological order, use node.descendants; for just leaf nodes, use node.leaves. To highlight the ancestors of a given node on mouseover, use node.ancestors. To generate an array of {source, target} links for a given hierarchy, use node.links; this replaces treemap.links and similar methods on the other layouts. The new node.path method replaces d3.layout.bundle; see also d3.curveBundle for hierarchical edge bundling.
The hierarchy layouts have been rewritten using new, non-recursive traversal methods (node.each, node.eachAfter and node.eachBefore), improving performance on large datasets. The d3.tree layout no longer uses a node._ field to store temporary state during layout.
Treemap tiling is now extensible via treemap.tile! The default squarified tiling algorithm, d3.treemapSquarify, has been completely rewritten, improving performance and fixing bugs in padding and rounding. The treemap.sticky method has been replaced with the d3.treemapResquarify, which is identical to d3.treemapSquarify except it performs stable neighbor-preserving updates. The treemap.ratio method has been replaced with squarify.ratio. And there’s a new d3.treemapBinary for binary treemaps!
Treemap padding has also been improved. The treemap now distinguishes between outer padding that separates a parent from its children, and inner padding that separates adjacent siblings. You can set the top-, right-, bottom- and left-outer padding separately. There are new examples for the traditional nested treemap and for Lü and Fogarty’s cascaded treemap. And there’s a new example demonstrating d3.nest with d3.treemap.
The space-filling layouts d3.treemap and d3.partition now output x0, x1, y0, y1 on each node instead of x0, dx, y0, dy. This improves accuracy by ensuring that the edges of adjacent cells are exactly equal, rather than sometimes being slightly off due to floating point math. The partition layout now supports rounding and padding.
The circle-packing layout, d3.pack, has been completely rewritten to better implement Wang et al.’s algorithm, fixing major bugs and improving results! Welzl’s algorithm is now used to compute the exact smallest enclosing circle for each parent, rather than the approximate answer used by Wang et al. The 3.x output is shown on the left; 4.0 is shown on the right:
<img alt="Circle Packing in 3.x" src="https://raw.githubusercontent.com/d3/d3/master/img/pack-v3.png" width="420" height="420"> <img alt="Circle Packing in 4.0" src="https://raw.githubusercontent.com/d3/d3/master/img/pack-v4.png" width="420" height="420">
A non-hierarchical implementation is also available as d3.packSiblings, and the smallest enclosing circle implementation is available as d3.packEnclose. Pack padding now applies between a parent and its children, as well as between adjacent siblings. In addition, you can now specify padding as a function that is computed dynamically for each parent.
The d3.rebind method has been removed. (See the 3.x source.) If you want to wrap a getter-setter method, the recommend pattern is to implement a wrapper method and check the return value. For example, given a component that uses an internal dispatch, component.on can rebind dispatch.on as follows:
component.on = function() {
var value = dispatch.on.apply(dispatch, arguments);
return value === dispatch ? component : value;
};
The d3.functor method has been removed. (See the 3.x source.) If you want to promote a constant value to a function, the recommended pattern is to implement a closure that returns the constant value. If desired, you can use a helper method as follows:
function constant(x) {
return function() {
return x;
};
}
Given a value x, to promote x to a function if it is not already:
var fx = typeof x === "function" ? x : constant(x);
The d3.interpolate method no longer delegates to d3.interpolators, which has been removed; its behavior is now defined by the library. It is now slightly faster in the common case that b is a number. It only uses d3.interpolateRgb if b is a valid CSS color specifier (and not approximately one). And if the end value b is null, undefined, true or false, d3.interpolate now returns a constant function which always returns b.
The behavior of d3.interpolateObject and d3.interpolateArray has changed slightly with respect to properties or elements in the start value a that do not exist in the end value b: these properties and elements are now ignored, such that the ending value of the interpolator at t = 1 is now precisely e
Nothing published for this version
One column per quarter.