inst/www/d3/d3-jetpack/README.md

d3-jetpack is a set of nifty convenience wrappers that speed up your daily work with d3.js

jetpack

(comic by Tom Gauld)

Usage

If you use NPM, npm install d3-jetpack. Otherwise, download the latest d3v4+jetpack.js.

Here's what's in the package:

# selection.append(selector) <>

Modifies append so it adds classes and ids.

selection.append("div.my-class");
selection.append("div.first-class.second-class");
selection.append("div#someId");
selection.append("div#someId.some-class");

# selection.insert(selector) <>

Works with insert, too:

selection.insert("div.my-class");

# selection.appendMany(array, selector) <>

Instead of making an empty selection, binding data to it, taking the enter selection and appending elements as separate steps:

selection.selectAll('div.my-class')
  .data(myArray)
  .enter()
  .append('div.my-class');

use appendMany:

selection.appendMany(myArray, 'div.my-class');

# selection.at(name[, value]) <>

Works like d3v3's .attr. Passing an object to name sets multiple attributes, passing a string returns a single attribute and passing a string & second argument sets a single attribute.

To avoid having to use quotes around attributes and styles with hyphens when using the object notation, camelCase keys are hyphenated. Instead of:

selection
    .attr('stroke-width', 10)
    .attr('text-anchor', 'end')
    .attr('font-weight', 600)

or with d3-selection-multi:

selection.attrs({'stroke-width': 10, 'text-anchor': 'end', 'font-weight': 600})

you can write:

selection.at({fontSize: 10, textAnchor: 'end', fontWeight: 600})

With syntax highlighting on, it is a little easier to see the difference between keys and values when everything isn't a string. Plus there's less typing!

# selection.st(name[, value]) <>

Like at, but for style. Additionally, when a number is passed to a style that requires a unit of measure, like margin-top or font-size, px is automatically appended. Instead of

selection
    .style('margin-top', height/2 + 'px')
    .style('font-size', '40px')
    .style('width', width - 80 + 'px')

The + pxs can also be dropped:

selection.st({marginTop: height/2, fontSize: 40, width: width - 80})

# d3.selectAppend(selector) <>

Selects the first element that matches the specified selector string or if no elements match the selector, it will append an element. This is often handy for elements which are required as part of the DOM hierachy, especially when making repeated calls to the same code. When appending it will also add id and classes, same as Jetpack's append

d3.selectAppend('ul.fruits')
    .selectAll('li')
    .data(data)

# d3.parent() <>

Returns the parent of each element in the selection:

d3.selectAll('span')
    .style('color', 'red')
  .parent()
    .style('background', 'yellow')

This might mess with the joined data and/or return duplicate elements. Usually better to save a variable, but sometimes useful when working with nested html.

# selection.translate(xyPosition, [dim]) <>

How I hated writing .attr('transform', function(d) { return 'translate()'; }) a thousand times...

svg.append('g').translate([margin.left, margin.top]);
circle.translate(function(d) { return  [x(d.date), y(d.value)]; });

If you only want to set a single dimension you can tell translate by passing 0 (for x) or 1 (for y) as second argument:

x_ticks.translate(d3.f(x), 0);
y_ticks.translate(d3.f(y), 1);

HTML is supported as well! translate uses style transforms with px units if the first element in the selection is HTML.

svg_selection.translate([40,20]); // will set attribute transform="translate(40, 20)"
html_selection.translate([40,20]); // will set style.transform = "translate(40px, 20px)"

# selection.tspans(array) <>

For multi-line SVG text

selection.append('text')
    .tspans(function(d) {
        return d.text.split('\n');
    });
selection.append('text').tspans(['Multiple', 'lines'], 20);

The optional second argument sets the line height (defaults to 15).

# d3.wordwrap(text, [lineWidth]) <>

Comes in handy with the tspans:

selection.append('text')
    .tspans(function(d) {
        return d3.wordwrap(text, 15);  // break line after 15 characters
    });

# d3.f(key) <>

d3.f takes a string|number and returns a function that takes an object and returns whatever property the string is named. This clears away much of verbose function(d){ return ... } syntax in ECMAScript 5:

x.domain(d3.extent(items, function(d){ return d.price; }));

becomes

x.domain(d3.extent(items, d3.f('price'));

d3.f even accepts multiple accessors and will execute them in the order of appearance. So for instance, let's say we have an array of polygon objects like this { points: [{x: 0, y: 3}, ...] } we can get the first y coordinates using:

var firstY = polygons.map(d3.f('points', 0, 'y'));

Since we use this little function quite a lot, we usually set var ƒ = d3.f (type with [alt] + f on Macs). Also, in @1wheel's blog you can read more about the rationale behind ƒ.

# d3.ascendingKey(key) <>

# d3.descendingKey(key) <>

These functions operate like d3.ascending / d3.descending but you can pass a key string or key function which will be used to specify the property by which to sort an array of objects.

var fruits = [{ name: "Apple", color: "green" }, { name: "Banana", color: "yellow" }];
fruits.sort(d3.ascendingKey('color'));

# d3.nestBy(array, key) <>

Shorthand for d3.nest().key(key).entries(array). Returns an array of arrays, instead of a key/value pairs. The key property of each array is equal the value returned by the key function when it is called with element of the array.

d3.nest()
    .key(ƒ('year'))
    .entries(yields)
    .forEach(function(d){
        console.log('Count in ' + d.key + ': ' + d.values.length) })

to

d3.nestBy(yields, ƒ('year')).forEach(function(d){
    console.log('Count in ' + d.key  + ': ' + d.length) })

# d3.loadData(file1, file2, file3, ..., callback) <>

Takes any number of files paths and loads them with queue, d3.csv and d3.json. After all the files have loaded, calls the callback function with the first error (or null if there are none) as the first argument and an array of the loaded files as the second. Instead of:

d3.queue()
    .defer(d3.csv, 'state-data.csv')
    .defer(d3.tsv, 'county-data.tsv')
    .defer(d3.json, 'us.json')
    .awaitAll(function(err, res){
        var states = res[0],
            counties = res[1],
            us = res[2]
    })

if your file types match their extensions, you can use:

d3.loadData('state-data.csv', 'county-data.tsv', 'us.json', function(err, res){
    var states = res[0],
        counties = res[1],
        us = res[2]
})

# d3.round(x, precisions) <>

A useful short-hand method for +d3.format('.'+precision+'f')(x) also known as +x.toFixed(precision). Note that this code is fundamentally broken but still works fine 99% of the time.

d3.round(1.2345, 2) // 1.23

# d3.clamp(min, val, max) <>

Short for Math.max(min, Math.min(max, val)).

d3.clamp(0, -10, 200) // 0
d3.clamp(0, 110, 200) // 110
d3.clamp(0, 410, 200) // 200

# d3.attachTooltip(selector) <>

Attaches a light weight tooltip that prints out all of an objects properties on click. No more > d3.select($0).datum()!

d3.select('body').selectAppend('div.tooltip')

circles.call(d3.attachTooltip)

For formated tooltips, update the html of the tooltip on mouseover:

circles
    .call(d3.attachTooltip)
    .on('mouseover', function(d){
      d3.select('.tooltip').html("Number of " + d.key + ": " + d.length) })

Make sure to add a <div class='tooltip'></div> and that there's some tooltip css on the page:

.tooltip {
  top: -1000px;
  position: fixed;
  padding: 10px;
  background: rgba(255, 255, 255, .90);
  border: 1px solid lightgray;
  pointer-events: none;
}
.tooltip-hidden{
  opacity: 0;
  transition: all .3s;
  transition-delay: .1s;
}

@media (max-width: 590px){
  div.tooltip{
    bottom: -1px;
    width: calc(100%);
    left: -1px !important;
    right: -1px !important;
    top: auto !important;
    width: auto !important;
  }
}

# d3.conventions([options]) <>

d3.conventions() appends an svg element with a g element according to the margin convention to the page and returns an object with the following properties:

totalWidth, totalHeight, margin: size of the svg and its margins

width, height: size of svg inside of margins.

parentSel: d3.selection of the element the svg was appended to. Defaults to d3.select("body"), but like every other returned value, can be specified by passing in an object: d3.conventions({parentSel: d3.select("#graph-container"), totalHeight: 1300}) appends an svg to #graph-container with a height of 1300.

svg: g element translated to make room for the margins

x: Linear scale with a range of [0, width]

y: Linear scale with a range of [height, 0]

xAxis: Axis with scale set to x and orient to "bottom"

yAxis: Axis with scale set to y and orient to "left"

drawAxis: Call to append axis group elements to the svg after configuring the domain. Not configurable.



Try the d3r package in your browser

Any scripts or data that you put into this service are public.

d3r documentation built on Oct. 2, 2023, 5:08 p.m.