Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

3 Key Insights That Make D3.js Easy to Learn

DZone's Guide to

3 Key Insights That Make D3.js Easy to Learn

A D3.js expert discusses how newcomers to this JavaScript library can more easily approach it's seemingly difficult to work with structure.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

The other day somebody asked me how to learn D3.js from scratch. I quipped that it took me writing a book to really learn it. It's one hell of a library.

Most people don't go that far. They don't have to. Most people start with a problem, find similar examples, do some copypasta, tweak until it works, and end up with a working visualization they don't understand. You'd be surprised how few people actually understand how their D3 data viz works.

But the idea that there's only 1 or 2, maybe 3, key concepts you have to grok to understand every D3 example out there ... it kept me up at night. What are those 3 key insights into D3?

1) Data Manipulation vs. DOM Manipulation

All D3 examples are split into two parts: data manipulation and DOM manipulation. First, you prep your values, then you render.

You have to go through many examples to notice what's going on. Inference learning is hard. Most beginners miss this pattern and it makes D3 look more confusing than it is.

Let's take an example from D3's docs, a bar chart with a hover effect.

Mike Bostock, the creator of D3, built this chart in 43 lines of code. Here they are:

There are two parts to this code: data manipulation and DOM manipulation.

Image title

Bostock here first prepares his data:

  • Some sizing variables (margin, width, height).
  • Two scales to help with data-to-coordinates conversion (x, y).
  • Loads his dataset (d3.tsv) and updates his scales' domains.
  • Uses scales to calculate attributes during DOM manipulation.

In the DOM manipulation part, he puts shapes and objects into an SVG. This is the part you then see in the browser.

DOM manipulation in D3 happens via D3 selections. They're a lot like jQuery $(something). Personally, I like to do this part with React as described in my book, React+D3v4.

Here Bostock does a few things:

  • Selects the <svg> node (d3.select).
  • Appends a grouping <g> node (.append) with an SVG positioning attribute (translate).
  • Adds a bottom axis by appending a <g>, moving it, then calling d3.axisBottom on it. D3 has built-in axis generators.
  • Adds a left axis using the same approach but rotating the ticks.
  • Appends a text label "Frequency" to the left axis.
  • Uses selectAll.data to make a virtual selection of .bar nodes and attach some data, then for every new data value (.enter), appends a <rect> node and gives it attributes.

That last part is where people get lost. It looks like magic. I've been using D3 for years and it still looks like magic.

It's a declarative approach to rendering data. Works great, hard to understand. That's why I do it in React instead.

You can think of .enter as a loop over your data and everything chained after .enter is your loop's body. Sort of like doing data.map(d => append(rect).setManyAttributes())

Savvy?

2) Scales

Scales are D3's most versatile concept. They help you translate between two different spaces. Like, mathematical spaces.

They're like the mathematical functions you learned about in school. A domain maps to a range using some sort of formula.


Colored shapes in the domain map to colors in the range. No formula for this one, which makes it an ordinal scale.

let shapes = d3.scaleOrdinal()
                 .domain(['red triangle', 'orange rectangle', ...)
                 .range(['red', 'orange', ...)

Once you have this scale, you can use it to translate from shapes to colors. shapes('red triangle') returns 'red' for example.

Many different types of scales exist. Linear, logarithmic, quantize, etc. Any basic transformation you can think of exists. The rest you can create by writing custom scales.

You're most often going to use scales to turn your data values into coordinates. But other use cases exist.

3) D3 Layouts

Sure .enter.append looks like magic, but D3 layouts are the real mind=blown of the D3 ecosystem. They take your input data and return a full-featured visualization thing.

But here's a key insight about the magic of layouts: they're the data part.

You take a forceLayout for example and feed it your data. It returns an object with a tick event callback.

var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) { return d.id; }))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));

This simulation now handles everything about rendering nodes. It changes their positions on every tick callback.

But it is up to you to render them. A layout handles your data viz in the abstract. You're still the one in control of rendering.

For a force layout, you have to update the DOM on every tick of the animation. For circle packing, you render it once.

It took me a while to get this, but, once I did, all the fancy looking visualizations started to make sense.

Fin

To summarize, you need to grok 3 key insights for D3 to make sense. Once they click, a whole new world opens up.

  1. Code is split into data and DOM manipulation.
  2. Scales are great and used a lot.
  3. You're always in control of rendering.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,d3.js ,javascript libraries

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}