Introduction to D3

What is D3?

D3 is a data visualization library written in JavaScript. It stands for Data-Driven Documents where Document stand for the DOM or the Docucment Object Model of a wweb page.

What D3 is not?

D3 does not have prebuilt visualizations – data visualization components like charts.

Only works with modern browsers – not compatible with the older versions.

Compatible with web standards so no plugins required like Flash, Silverlight or Java.

Why D3?

Building visualizations with vanilla JavaScript or SVG can quickly become a tedious, difficult task. Let’s look at an SVG example.

See the Pen SVG Graph by Sean Amarasinghe (@szaranger) on CodePen.

D3 has declarative syntax, which encapsulates the implementation and provides us with an intuitive interface.

d3.select('body')
  .selectAll('div')
  .attr('class', 'bar')
  .style('height', function (d) {
    return d * 20 + 'px';
  });

This might not make sense just yet, you can see we are using a function which knows about our data, to set the height.

Using D3

D3 does the hard work for us by automating the repetitive hard bits. D3 comes packed with useful helpers we can use. Let’s look at what D3 gives us.

  • Helpers
  • Scales
  • Axes
  • Data

To understand above features, let’s start by creating a basic graph.

See the Pen D3 Basic Chart by Sean Amarasinghe (@szaranger) on CodePen.

Helpers

D3 has helper functions like min and max values of a data set.

var dataset = [ 1, 2, 3, 4, 5, 8 ];

d3.min(dataset); // 1

The source data to D3 is built of Plain Old JavaScript objects, or POJOS.

D3 functions commonly take callbacks which in turn takes two arguments element and index. These parameters are usually called passed in as d and i.

var dataset = [ 1, 2, 3, 4, 5, 8 ];

d3.max(dataset, function(d, i) { return d.amount; }); // 8

Scales

Scales are objects in D3 that help map values across coordinate systems.

Scales have the following attributes:

  • Configured with a domain and a range
  • Map from the data to teh screen space
  • There are different types of scales – linear and logarithmic

Domain – The data space which its units are our source units.

Range – The screen pixels

Let’s look at how we can implement a y-scale example.

var y = d3.scale.linear()
  .domain([0, 100])
  .range([100, 0]);

y(0); // 100
y(50); // 50
y(100); //0

Now let’s apply scaling to our graph.

See the Pen D3 Scaling by Sean Amarasinghe (@szaranger) on CodePen.

We are overriding the default domain and range by specifying the domain and range using chained syntax.

var yScale = d3.scale.linear()
    .domain([0, 50])
    .range([0, height]);

We were able to bypass the step of figuring out how to map our initial interval (domain) onto our new interval (range).

Axes

D3 has helpers we can use to draw an axis for our graph. D3.js Axis component allows for easy addition of a horizontal-axis and vertical-axis to any graph.

See the Pen D3 Scaling Basic by Sean Amarasinghe (@szaranger) on CodePen.

To add the axis to the SVG graph, we will have to call the axis function on a selection.

var xAxis = d3.svg.axis()
  .scale(axisScale)
  .orient('below')
  .ticks(4);

We use the call() operator to call the axis function.

var xAxis = d3.svg.axis()
  .scale(axisScale)
  .orient('below')
  .ticks(4);

Data

Data binding is done differently with D3 selections. They’re powerful because the same selection can be updated for different data later on. Updating is the most powerful part of selections.

D3.js figures out for you how to draw the vertical axis line, the vertical axis ticks, the correct spacing of axis ticks to make the axis visually appealing and many other things.

d3.select(String selector) -> (d3.selection)
Selections

D3 selections are a group of elements that match a query.

D3.max

Let’s look at how to use D3’s max method to normalize your dataset visually within the specific bounds of a variable domain.

var initialScaleData = [0, 10, 30, 20, 50, 40, 70, 60, 90, 80, 100];

d3.max(initialScaleData); // 100

As you can see, D3.max calculates the maximum value of an array. By using this method we can create a complicated chart as the following.

See the Pen D3: Max by Sean Amarasinghe (@szaranger) on CodePen.

Same as above we can use d3.min to calculate the minimum value of an array.

rangeBands

We can use rangeBands to horizontally scale our D3 charts. When building a chart such as a bar chart in d3, you’ll want an evenly divided space on your x axis. You could divide the space up with your own manual calculations, accounting for space available, bar width, and inner and outer padding. Or, you could have d3 do the calculation for you via a rangeBand.

See the Pen D3: rangeBands by Sean Amarasinghe (@szaranger) on CodePen.

So for building a chart such as a bar chart in d3, you’ll want an evenly divided space on your x axis. You could divide the space up with your own manual calculations, accounting for space available, bar width, and inner and outer padding. Or, you could have d3 do the calculation for you via a rangeBand.

Color Scales

Let’s explore the use of color scales in our D3 charts.

See the Pen D3: Color Scales by Sean Amarasinghe (@szaranger) on CodePen.

We can handle the background color of a filled object with fill, its transparency with opacity, the color of the outline with stroke and the transparency of that color with stroke-opacity.

D3 has two color objects: d3_Rgb and d3_Hsl, which describe colors in the two of the most popular color spaces: red/green/blue, and hue/saturation/light.

Quantitative Scales

In D3 quantitative scales allow you do easily divide aspects of your chart evenly based on the dataset. Let’s find out the variety of scaling options available in D3.

See the Pen D3: Quantitative Scales by Sean Amarasinghe (@szaranger) on CodePen.

Margins

Let’s look at how to add margins to your D3 charts to give them the room they deserve.

See the Pen D3: Margins by Sean Amarasinghe (@szaranger) on CodePen.

Scatter Plot

D3 offers a variety of charts you can work with. Let’s convert the bar chart into a basic scatter (or bubble) chart.

See the Pen D3: Scatter Plot by Sean Amarasinghe (@szaranger) on CodePen.

Conclusion

D3 gives the front-end devloper enormous potential in dlivering complecated yet sophisticated data visualizations.

The Github source for this article can be found in here.

Be first to comment

Leave a Reply