Beginner's D3.js Tutorial: Learn Data Visualization with JS
Tags: javascript, datascience, tutorial, technology
Published: 2021-03-29 17:58:49

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.
 
<br>
 
**Here’s what we’ll cover today:**
 
* [What is D3.js?](#what)
* [D3.js environment setup](#setup)
* [Fundamental components of D3.js](#components)
* [Data visualization examples](#examples)
* [Advanced concepts to learn next](#next)

<br>

<h4><b> Master D3.js fast with hands-on practice</b></h4>
 
Practice creating dozens of different interactive graphs with step-by-step lessons.
 
<b>[Introduction to Visualization Using D3.js](https://www.educative.io/courses/introduction-to-visualization-using-d3-js)</b>

<br>
 
<a name="what"></a>
 
## What is D3.js?
**D3.js (Data-Driven-Documents)** is an open-source JavaScript library that lets you create dynamic data visualizations in web browsers using SVC, [HTML 5](https://www.educative.io/blog/revamp-front-end-skills), 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.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ejn6bsv9imor7kmwb6mg.PNG)

While [big data](https://www.educative.io/blog/what-is-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:
- Make quick decisions based on large data sets
- Understand overarching market trends
- Communicate information at a glance
- Find errors in recorded data

<br>
 
### Top Features of D3.js 
- **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.

<br>
 
<a name="setup"></a>
 
## D3.js Environment Set up 
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:
 
```html
<!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](https://www.educative.io/blog/best-python-ides-ce-2021) (IDEs) are:
- Visual Studio Code
- Eclipse
- Sublime Text
 
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!


<br>
<a name="components"></a>
 
## Fundamental components of D3.js
Now we'll take a look at the fundamental components of any D3 project. The important components are:
- **Selections**, used to select DOM elements for manipulation
- **DOM manipulation**, used to add or modify text within DOM elements
- **Method Chaining**, used to create a pipeline of methods that each transform an object.
- **Data Joins**, used to bind data to a selected element to make data-based manipulations easier.

<br>

## D3 Selections
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()`.

<br>

### Select()
 
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.

> The first code snippet is our HTML and the second is our JavaScript file.

```html
<head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
	<div>Welcome to Educative</div>
    <div>Introduction to D3.js</div>
</body>
</html>
```

```js
d3.selectAll('div').style("color","green");
```

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.

<br>

## DOM Manipulation with D3
Now we'll take a look at the most common DOM manipulation methods, `text()`, `append()`, `remove()`, `style()`, and `attr()`. 

<br>

### text()
The `text()` method manipulates DOM elements and is generally used to add or modify the text inside DOM elements.
 

```html
<head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
	<div></div>
</body>
</html>
```

```js
d3.select('div').text("I am adding text");
```

We first use the `select()` method to select `div` elements. Then we use the `text()` method to add our text to the `div` element.

<br>

### append()
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.

```html
<head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
	<div>Introduction to Visualization using D3.js</div>
</body>
</html>
```

```js
d3.select("body").append("div").text("Appending new div tag")
```

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.

<br>

### remove()
The `remove()` method is used to remove a selected HTML element.

```html
<head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
	<div>1st div tag</div>
    <div>2nd div tag</div>
</body>
</html>
```

```js
d3.select("div").remove()
```

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.
 
<br>

### style()
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.

```html
 <head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
	<div>Showing effect of the style method</div>
</body>
</html>
```

```js
d3.select("div").style("color","blue").style("font-size","30px")
```


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.

<br>

### attr()
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.

```html
<head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
	
</head>
<body>
	<div>Showing effect of the attr method</div>
</body>
</html>
```

```js
 d3.select("div").attr("class","error");
```

```css
.error {
    color: blue;
    font-size: 30px
    }
```

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.

<br>
 
 
<div style="background-color:#F1F1FF;padding-left: 10px;padding-top:1px;padding-bottom:1px;">

#### Keep learning D3.js
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. 

<b>[Introduction to Visualization Using D3.js](https://www.educative.io/courses/introduction-to-visualization-using-d3-js)</b>
</div>

<br>
 
## Method Chaining
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](https://www.educative.io/blog/what-is-functional-programming-python-js-java), 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. 

```js
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 apply 3 methods with a single call to the original input.
 
You can also write method chains on seperate lines to aid readability:
```js
d3.select("div")
.style("color","blue")
.style("font-size","30px")
```

<br>

## Data Joins 
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()`. 

<br>

### datum()
The `datum()` method joins data points with a single D3 selection. 


```html
<head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
	<p></p>
</body>
</html>
```

```js
d3.select("body")
  .select("p")
  .datum(["10"])
  .text(function(d) { return d; });
```

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.

<br>

### data()
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.

```html
<head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
	<p></p>
   <p></p>
   <p></p>
</body>
</html>
```

```js
d3.select("body").selectAll("p")
   .data([10, 20, 30])
   .text(function(d) { return d; });
```

 
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.
 
<Br>
 
### enter()
The `enter()` method is used to bind elements when there are more selected elements than there are elements in the array.

```html
<head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
	<p></p>
	<p></p>
	<p></p>
</body>
</html>
```

```js
d3.select("body").selectAll("p")
   .data([10, 20, 30, 50, 70])
   .text(function(d) { return d; })
   .enter()
   .append("p")
   .text(function(d) { return d; });
```

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.


<br>
 
<a name="examples"></a>
 
## Data Visualization Examples
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.

<br>
 
### SVG with D3.js
To create an SVG with D3, we'll need to include the `svg` tag inside our HTML file.
 
```html
<body>
     <svg>content</svg>
</body>
```
 
D3 also has a "line" graphical element that can be configured with `attr()`.

```html
<head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
</body>
</html>
```

```js
var svg = d3.select("body") //create Svg element
   .append("svg")
   .attr("height",200 )
   .attr("width", 200)
   .style("border", "solid 8px red");
 
svg.append("line")
   .attr("x1", 50)
   .attr("y1", 30)
   .attr("x2", 150)
   .attr("y2", 100)
   .attr("stroke", "black")
   .attr("stroke-width","2px");
```

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.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehwy6z1thgnvdwzrl0jt.PNG)

<br>

### Pie Chart with D3.js
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. 

```html
<head>
	<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
</body>
</html>
```

```js
var margin = {top: 20, right: 20, bottom: 60, left: 80},
     width = 500 - margin.left - margin.right,
     height = 500 - margin.top - margin.bottom;
var data = [
  {language:  "Python", value: 30},
  {language:  "Java", value: 20},
  {language:  "C/C++", value: 15},
  {language:  "Javascript", value: 35},
  {language:  "PHP", value: 15},];
colors=["#00A5E3","#FF96C5","#00CDAC","#FFA23A","#74737A"]  
var svg = d3.select("body") //create Svg element
   .append("svg")
   .attr('width', width + margin.right + margin.left)
   .attr('height', height + margin.top + margin.bottom)
   .style("border", "solid 1px red")
    .attr("transform","translate(200,0)");                 
var chart=svg.append('g')
   .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
   .attr('width', width)
   .attr('height', height)
var pie=d3.pie() 
        .value(d => d.value)
var color_scale=d3.scaleOrdinal()
              .domain(data.map(d=>d.language))
              .range(colors)
let arc=d3.arc()
       .outerRadius(150)
       .innerRadius(0)
var p_chart=chart.selectAll("pie")
     .data(pie(data))
     .enter()
     .append("g")
     .attr('transform', 'translate(170,230)') 
p_chart.append("path")
     .attr("d",arc) 
     .attr("fill",d=>{
       return color_scale(d.data.language);
     })     
p_chart.append("text")
      .text(function(d){ return d.data.language})
      .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")";  }) 
      .style("text-anchor", "middle")   
```

**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.

 
<br>
 
<a name="next"></a>
 
 
## Advanced concepts to learn next
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:
- Scale and rescaling
- User interactivity
- Hierarchical mapping
- Advanced chart forms

To help you get there, Educative has created [**Introduction to Visualization Using D3.js**](https://www.educative.io/courses/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!*

<br>
 
### Continue reading about JavaScript and Data Science
- [What is jQuery? Learn the most popular JavaScript library](https://www.educative.io/blog/what-is-jquery-javascript-library)
- [Data Analysis Made Simple: Python Pandas Tutorial](https://www.educative.io/blog/python-pandas-tutorial)
- [What is Big Data? Characteristics, Types, and Technologies](https://www.educative.io/blog/what-is-big-data)