D3.js is a powerful JavaScript library for data visualization. Unlike many data visualization tools that use Python, D3.js is entirely controlled with front-end skills like JavaScript, CSS, and HTML. With JS driven code, built-in rending functionalities, and automatic animation, D3 has consistently stood out as the best data visualization tool for front-end developers.
Today, we’ll help you get started with D3.js components and give you hands-on practice with creating your first visualizations.
Master D3.js fast with hands-on practice
Practice creating dozens of different interactive graphs with step-by-step lessons.
D3.js (Data-Driven-Documents) is an open-source JavaScript library that lets you create dynamic data visualizations in web browsers using SVC, HTML, and CSS. It was created by Mike Bostock in 2011 as a spiritual successor to Protovis. D3.js specializes in representing large data sets in a digestible and interactive means.
While most data visualization tools require Python, D3.js visualizations are created entirely using JavaScript. This allows frontend developers to add advanced data visualization to their UIs without the hassle of learning a new language.
Many advanced data manipulation and visualization functions are built-in and implemented, meaning that a new D3.js user can create effects that would otherwise require years of experience.
For example, D3.js features built-in graph styles for anything from a simple pie chart to an interactive circular barplot.
In short, D3.js is designed to be quick to pick up and powerful in the hands of current front-end developers.
Here’s an example of a D3.js pie chart that shows the top programming languages to use in 2020.
While big data is hard to comprehend, visualizations are much more approachable. A well done visually can perfectly convey thousands of data points into a cohesive and actionable trend.
Data visualization helps to:
Uses Web Standards: Uses the established standards SVG, HTML, and CSS to make it compatible with existing technologies.
Data-Driven: D3 can use static data or fetch it from remote servers in several formats like Arrays, Objects, CSV, JSON, or XML.
DOM Manipulation: D3 allows you to manipulate the Document Object Model (DOM) using your data.
Dynamic Properties: D3 provides dynamic properties and elements. Properties can be specified as functions of data which then edit your elements. In other words, your data defines the style of your visualization.
Types of visualization: D3 features dozens of built-in graph formats for common applications like ranking, correlation, and distribution.
Custom Visualizations: D3 allows you to create custom visualizations from scratch or by tweaking current graph formats.
Transitions and Animation: D3 provides built-in animation functions the transition()
, duration()
, delay()
and ease()
functions, which automatically animate features of your graph based on user interaction, timed transitions, or other events.
You’ll have to set up a D3.js environment before you get hands-on. The four components of a D3.js environment are the D3 library, a web server, a text editor, and a web browser.
You can use the D3 library by linking it directly to your HTML page from the Content Delivery Network (CDN). Using CDN will allow you to work with D3 without downloading the source code.
Include D3 by entering the CDN url for D3 in your head
section:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
// write your d3 code here..
</script>
</body>
</html>
For web servers, most browsers server local HTML files directly to the browser. You can also a web server like Apache if you’re more comfortable with that.
Your text editor should have JavaScript support. Some great Integrated Development Environments (IDEs) are:
D3 works on all browsers except IE8 and lower. For this tutorial, I’ll be using Google Chrome. Once you have all of these things, you’re ready to get started!
Now we’ll take a look at the fundamental components of any D3 project. The important components are:
Selection is the beginning of most D3 method chains as it dictates which elements will be affected by later methods. There are two methods for selection in D3.js, select()
and selectAll()
.
The select()
method is used to select a single instance of a given HTML tag. If the specified tag is not present, then it will return an empty selection. If multiple instances of the selected tag are present, then it will select the first element only.
Let’s run the famous “hello world” program for D3.js using the select()
method.
First, we select the div
's content by calling the select()
method on lines 1 and 2. Then we store the selected content in variable s
. Finally, we show the stored selected content by calling console.log(s)
.
Congratulations on your first D3.js application!
The other method for selection is selectAll()
which allows you to select multiple instances of an HTML tag. If multiple instances are present, it will select all of them. If the tag is not present, it will return an empty selection.
Above, we select all the HTML div
tags using the selectAll()
method to change their color to green.
First, we select all text under the div
tag using the selectAll()
method. Then, we then use the style()
method to add style to selected text.
Now we’ll take a look at the most common DOM manipulation methods, text()
, append(),
remove(),
style(), and
attr()`.
The text()
method manipulates DOM elements and is generally used to add or modify the text inside DOM elements.
We first use the select()
method to select div
elements. Then we use the text()
method to add our text to the div
element.
The append()
method is used to add new a new HTML element to the end of the selected element. Let’s create a new div
element inside the body
tag and add text to it using the text()
method.
One div
tag is already present inside the body tag in the HTML file. In line 1, we use the append()
method to add a new div element to the HTML file. Then, we have added the text, “Appending new tag” using the text() method.
The remove()
method is used to remove a selected HTML element.
The select()
method selects the first div
element. Then, we use the remove()
method to remove the selected element. By the end, only the second div
element is shown.
D3.js provides the style()
method to set the style of selected DOM elements. Style is set in a format similar to CSS but can only change one attribute at a time. The first parameter of style
is always the attribute you want to edit and the second parameter is the new value.
As before, we start by selecting the div
tag then change the color to blue with the first style()
method and change the font with the second. Each style()
method can only change a single attribute.
Instead of calling style()
twice, we can call attr()
once. The attr()
method links your element to a CSS style sheet and applies the sheet’s settings to any selected elements.
It is also used to define the attributes of a geometric figure, which we’ll see later.
Our attr()
method links the selected div
element to our CSS sheet. The first parameter defines what type the sheet is and the second parameter specifies the class name to select.
This allows D3 to conform the selected element to have its color and font-size attributes match the CSS sheet.
Learn D3.js without scrubbing through videos.
Educative’s text-based courses make learning quick and efficient with skimmable lessons and hands-on coding environments.
Method chaining is a technique that lets you string multiple methods together. The output of the first method will be fed as input to the second method and so on until the chain is complete.
Similar to function composition in functional programming, method chaining lets you combine simple methods to create complex behaviors.
You’ve already been using this throughout the tutorial when we use select()
and another method on the same element.
This previous example is a great example.
d3.select("div").style("color","blue").style("font-size","30px")
First, we pass div
as input to the select()
method. Then select()
returns a selection element which is used as input for the style()
method. The first style()
then applies the style changes to the passed element. The newly styled element is then passed to the next style()
for another change. By the end, we’ll apply 3 methods with a single call to the original input.
You can also write method chains on seperate lines to aid readability:
d3.select("div")
.style("color","blue")
.style("font-size","30px")
Data joins allow us to bind selected elements to the data of an array. Binds are the main tool you’ll use to draw visualizations as they make your DOM manipulations more reactive to your data.
The three main methods for data joins are datum()
, data()
, and enter()
.
The datum()
method joins data points with a single D3 selection.
In the above example, we want to bind the data element with the HTML tag. In line 1, we select the p
tag using the select()
method. In line 3, we use the datum()
to bind 10
with the p
tag. In line 4, we use text()
to return the data associated with the p
tag.
We can use data()
to associate multiple data points with a set of D3 selections. This is useful when working with big data sets as it means you don’t need to bind each data point individually.
Here, we select three elements in the body using the selectAll()
method and bind each to a data point using data()
. The final line prints the data from the paired selection.
The enter()
method is used to bind elements when there are more selected elements than there are elements in the array.
Above we have three selected p
elements but 5 elements in the data()
array. This binds all possible elements in order until there are no unbound p
elements left. Then we use append to add additional p
elements until all can be bound.
Now that we know the components, we’ll see how we can use D3 to complete two different sample visuals. We’ll start with a simple line SVG to get you warmed up then show you how to create the pie chart from earlier in the article.
To create an SVG with D3, we’ll need to include the svg
tag inside our HTML file.
<body>
<svg>content</svg>
</body>
D3 also has a “line” graphical element that can be configured with attr()
.
From line 1 to line 5 in the JavaScript page, we have created the svg
tag inside the body
tag. With the help of the attr
method, we are defining the attributes of svg
.
From line 7 to line 13 in the JavaScript page, we have created a line inside the svg
tag and initialized attributes of the line with the help of the attr
method.
The following illustration shows how the line is positioned with respect to the origin which lies in the top left corner of the SVG canvas.
Now we will use d3.arc
and d3.pie
APIs to create a portion of the “Programming Languages Used in 2020” chart we saw at the beginning of the article.
Line 29-33: First, we have defined p_chart
. We have selected pie, which doesn’t exist, so it will return an empty selection. Now we are joining data()
with our return selection through data(pie(data))
. Then we have appended the g
tag for each data point.
Line 34-38 is where the pie chart is drawn with the help of an arc. With the help of ordinalScale()
, we have assigned a color to each arc.
Line 39-42: We have added the name of the language to the respective arc by using the text()
method. This text()
will be placed at the centroid of each arc with the help of the arc.centroid()
method.
As you can see, D3 allows you to create some eye-catching visuals with even just these basic components. As you continue to learn D3.js, here are some advanced concepts that will help you produce even better charts and graphs:
To help you get there, Educative has created Introduction to Visualization Using D3.js. Within you’ll find hands-on examples of every type of chart and learn how to manipulate your visuals with interactivity and scale.
By the end, you’ll be able to use your front-end JS skills to create data visualizations on par with the most seasoned data scientists.
Happy learning!
Free Resources