D3.js Cheatsheet



This D3.js cheatsheet provides a concise reference to key D3.js concepts, including selections, data binding, transitions, scales, axes, and interactivity. It covers advanced topics such as layouts, animations, and tooltips, with practical code examples for each feature. Use this guide as a fast resource for creating dynamic and interactive visualizations in D3.js.

Table of Contents

Selections

Selections: Methods for selecting and manipulating DOM elements in D3.js.

d3.select(): Select the first element matching the selector.

Example:

d3.select("svg")

d3.selectAll(): Selects all elements matching the selector.

Example:

d3.selectAll("circle")

selection.append(): Appends a new element to the selected elements.

Example:

d3.select("svg").append("circle")

selection.remove(): Removes the selected element from the DOM.

Example:

d3.select("rect").remove()

selection.attr(): Sets or retrieves an attribute.

Example:

d3.selectAll("circle").attr("r", 10)

selection.style(): Applies inline CSS styles.

Example:

d3.selectAll("circle").style("fill", "teal")

selection.classed(): Adds or removes a class.

Example:

d3.select("circle").classed("highlight", true)

Data Binding

Binding data to elements and handling data-driven updates.

selection.data(): Binds an array of data to elements.

Example:

d3.selectAll("circle").data(dataset).enter()

selection.enter(): Handles creating new elements when data exceeds existing elements.

Example:

d3.selectAll("circle").data(dataset).enter()

Accessing Data: Use anonymous functions to access bound data.

Example:

d3.selectAll("rect").attr("height", d => d.value);

Using Index (i): Optionally use index to manipulate elements.

Example:

d3.selectAll("rect").attr("x", (d, i) => i * 10);

Transitions

Transitions: Animating changes in attributes and styles over time.

selection.transition(): Creates a transition on the selected elements.

Example:

d3.selectAll("circle").transition().attr("cx", 100)

selection.duration(): Sets the duration of the transition.

Example:

d3.selectAll("circle").transition().duration(2000)

Chaining Transitions: Use .call() to chain transitions together.

Example:

selection.transition().attr("cx", xMap).call(endall, callback);

Scales

Scales: Mapping data values to visual representations using scales.

d3.scaleLinear(): Creates a linear scale function.

Example:

var xScale = d3.scaleLinear().domain([0, 100]).range([0, 500]);

d3.min() / d3.max(): Find the minimum or maximum in an array.

Example:

d3.min([10, 20, 30]) // 10

Axes

Creating and modifying axes for visualizing data scales.

d3.axisBottom(): Creates an axis generator.

Example:

var xAxis = d3.axisBottom(xScale);

axis.scale(): Specifies the scale to use with the axis.

Example:

xAxis.scale(xScale);

axis.ticks(): Specifies the number of ticks on the axis.

Example:

xAxis.ticks(5);

selection.call(): Used to call an axis method on a selection.

Example:

svg.append("g").call(xAxis);

Interactivity

Handling user interactions like clicks and mouse events.

selection.on(): Binds an event listener to elements.

Example:

d3.select("#button").on("click", function() {...});

Using this in event functions: Within an event listener, this refers to the element being acted upon.

Example:

d3.selectAll("rect").on("mouseover", function() {
    d3.select(this).classed("highlight", true);
});

Other JavaScript Utilities

Useful JavaScript functions for working with data and DOM.

Math.random(): Returns a random value between 0 and 1. 

Example:

Math.random() * 100;

Math.floor(): Rounds a number to the nearest integer.

Example:

Math.floor(10.8) // 10

array.push(): Appends a new item to an array.

Example:

numbers.push(6);

Attributes/Styles

Setting SVG attributes and inline styles dynamically.

var svgWrapper = d3.select("body").append("svg")
        .attr("width", 600).attr("height", 400);

Adding links to SVG and HTML elements using D3.js.

SVG: Uses xlink:href to link an SVG element (e.g., text) to a URL.

selection.select('text').attr("xlink:href", d => d.url);

HTML: Appends an anchor "<a>" element and sets its href attribute dynamically.

selection.append('a').attr('href', d => d.url).text(d => d.name);

Axis

Axis: Configuring and styling axes for data visualization.

Example:

var xAxis = d3.svg.axis().scale(xScale).orient("bottom")
.ticks(4).tickFormat(d3.time.format('%d %b %I%p'));

Color

Color: Working with color scales and schemes in D3.js.

var myCategory20 = d3.scale.ordinal().range([0x1f77b4, 0xaec7e8]);

General Update Pattern

Handling data updates with enter, update, and exit selections.

function update(data) {
        var text = svg.selectAll("text").data(data);
        text.enter().append("text").text(d => d);
        text.exit().remove();
    }

SVG Basics

SVG basics: Creating and manipulating SVG elements.

const svg = d3.select('body').append('svg')
        .attr('width', 500).attr('height', 500);
    svg.append('circle').attr('cx', 50).attr('cy', 50).attr('r', 20).style('fill', 'blue');

Data Joins

Data Joins: Associating data with elements and dynamically updating them.

Example:

const data = [10, 20,
30];\nd3.select('svg').selectAll('circle').data(data).enter().append('circle').attr('cx', (d, i) => i * 50
+ 50).attr('cy', 50).attr('r', d => d / 2);

Events

Handling user interactions with event listeners.

svg.selectAll('circle').on('click', (event, d) => console.log('Clicked', d));

Animations

Animations: Adding smooth transitions and animations to elements.

svg.selectAll('circle').transition().duration(1000)
        .attr('r', 40).style('fill', 'red');

Formatting

Formatting numbers, dates, and text in D3.js.

Example:

const format = d3.format('.2f');
console.log(format(1234.567)); 
const timeFormat = d3.timeFormat('%Y-%m-%d');
console.log(timeFormat(newDate()));

Zooming and Panning

Zooming: Implementing zoom and pan functionality for SVGs.

const zoom = d3.zoom().on('zoom', (event) => svg.attr('transform', event.transform));
    d3.select('svg').call(zoom);

Tooltips

Displaying contextual information on hover with tooltips.

const tooltip = d3.select('body').append('div').style('position', 'absolute')
        .style('visibility', 'hidden').text('Tooltip');
    svg.selectAll('circle').on('mouseover', () => tooltip.style('visibility', 'visible'))
        .on('mousemove', (event) => tooltip.style('top', `${event.pageY}px`).style('left', `${event.pageX}px`))
        .on('mouseout', () => tooltip.style('visibility', 'hidden'));
Advertisements