Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learn D3.js

You're reading from   Learn D3.js Create interactive data-driven visualizations for the web with the D3.js library

Arrow left icon
Product type Paperback
Published in May 2019
Publisher Packt
ISBN-13 9781838645571
Length 650 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Helder da Rocha Helder da Rocha
Author Profile Icon Helder da Rocha
Helder da Rocha
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Introduction FREE CHAPTER 2. Technical Fundamentals 3. Quick Start 4. Data Binding 5. Manipulating Data and Formatting 6. Scales, Axes, and Colors 7. Shape and Layout Generators 8. Animation and Interactivity 9. Visualizing Hierarchical Data 10. Visualizing Flows and Networks 11. Visualizing Geographical Data 12. Other Books You May Enjoy

Using D3

All that you need to start using D3 can be found at d3js.org where you can download and install the library as a single JavaScript file, a collection of standalone microlibraries, a CDN link, or an NPM installation script. The site also includes the official documentation, which covers the library in great detail, with hundreds of tutorials for beginners and advanced users, and thousands of online examples.

The D3 site is a great place to start because you can try out several examples of data visualizations created with D3. Just click on any hexagon and it will lead you to a page showing a D3 application and its source code. Most are published in GitHub and published using the Bl.ocks platform (bl.ocks.org), which is a huge portfolio based on GitHub source code. Newer projects use the Observable platform (observablehq.com), which contains interactive tutorials where you can edit the code and see changes in real time. These platforms are very popular among the D3 community. Many of these tutorials were designed by creators and major contributors of the D3 library, such as Mike Bostock, Jason Davies, and Philippe Riviere.

Take some time to explore these examples and see what you can create using D3.

The D3.js website is a showcase of the many different data visualizations you can create using this library

Environment setup

You don't need a sophisticated development environment to use D3. If you already develop Web applications using npm, you can install it with:

npm install d3

You can also add the d3.js file to a local folder after downloading the full library (default bundle) as a ZIP from the official website. Then you can import it to your HTML file using the <script> tag and a local relative path; for example (for the minified version):

<script src="js/d3/d3.v5.min.js"></script>

If you have a permanent web connection, it's probably simpler to use a CDN link:

<script src="https://d3js.org/d3.v5.min.js"></script>

For very simple applications that don't load external files, you can simply open the page in your browser from the file system. It's better to load the page using a web server. If you are using a code editor, it may already have a launch configuration or plugin that always starts a web server when you choose to load a page. You can also install a simple web server using npm, by using the following command:

npm install http-server –g

The preceding command will install it globally. Then, you can move to the directory where your files are located and simply type the following:

http-server

Then you can load your files from http://localhost:8080.

You can also develop D3 using online code editors, such as CodePen (codepen.io) or JSFiddle (jsfiddle.net). It’s also a great way to share your code.

Hello, world

Let's create a simple D3-powered data-driven visualization to test your configuration. Create a new HTML file in your development environment and import the D3 library, or import it into any HTML page using the <script> tag as shown in the last section. Then add an <svg> and a <script> block inside your page's <body> as follows:

<body>
<svg id="chart" width="600" height="200"></svg>
<script>
</script>
</body>

Now add the following array inside the <script> block:

const array = [100, 200, 300, 350, 375, 400, 500];

We will use that array to generate a series of dots. Type in the following code (you can ignore the comments), which consists of a series of chained commands:

d3.select("#chart")     // selects the svg element by id (like JQuery)
.selectAll("circle") // declares the elements we would like to create
.data([100]) // sets the data to drive the creation of the
// elements
.enter() // creates a selection to add elements per
// data item
.append("circle") // appends an element of this type to each
// data item
.attr("r", 10) // sets “r” attribute
.attr("cy", 100) // sets “cy” attribute
.attr("cx", d => d) // sets “cx” attribute (same as function(d) {
// return d; }

If your configuration is working correctly, when you load the page containing this code in a browser, you should see a single dot on the screen:

A dot on a screen created with D3. Code: HelloWorld/1-intro-d3.html

If you inspect the dot with your browser's JavaScript development tools, you will notice that the following code was generated inside the SVG:

<svg width="600" height="200">
<circle r="10" cy="100" cx="100"></circle>
</svg>

The preceding JavaScript code selects the <svg> element from the page and then selects all <circle> elements inside it. But there aren’t any, so the selection is empty. The next line, however, contains a data() command with a one-element array: [100]. The enter() command binds the data to the selection creating a selection of <circle> placeholders the same size as the data array. In this case, it will only contain one placeholder. Finally, the append() command, called in the context of this selection, appends a <circle> element to it, making it a child of the <svg> element.

The last three commands set attribute values and the last one takes a function and returns the element received by the function, which is used as the attribute's value. This element is the value 100 that was stored in the array passed to the data() command.

The code is available in the HelloWorld/1-intro-d3.html file from the GitHub repository for this chapter.

Now let's make some changes. Replace the [100] in the data() command with array. It will now reference the seven-element array we created before:

.data(array)

Run the page again. What happened? Consider the following screenshot:

Several dots added to the screen with positions driven by the data. Code: HelloWorld/2-binding.html

Now there are seven dots on the screen; the same number of dots as the data array. And each dot is positioned at a different horizontal position (which was defined by the cx property of the <circle>) that is set using values from the data array. We used the data array to drive the position of each circle.

Now skip a line and add this code after the selection (see HelloWorld/3-update.html):

setTimeout(function() {
d3.select("#chart").selectAll("circle")
.data([50, 75, 125, 225, 325, 425, 450])
.attr("r", 5)
.attr("cx", d => d)
.style("fill", "red")
}, 2000)

This code will run two seconds after the page loads and shows the circles in the positions defined by the first chain of commands. The function inside it selects the #chart SVG element again, and then all the circles inside it. But this time, these circles do exist. The data() command binds a new data array to the selection. No enter() command is called because there aren't any elements to be added.

The attr() commands are used to the circle's attributes. Only two attr()commands were called in the preceding code because we are only changing two attributes: the radius of the circle, and the position, which will now obtain its value from the new array. Besides that, we also used style() to change the color of the dots. If you run this file, two seconds later, the dots shrink, move to the left and become red:

The dots changed color, size, and position after an update. Code: HelloWorld/3-update.html

One very nice feature of D3 is how simple it is to animate transitions. You just need to chain a transition() command before the attributes and styles that changed. The default transition takes a quarter of a second. Let's make it a little longer by configuring duration. Add the following line between the data() command and the first attr(), to add a one-second transition during the data update:

.transition().duration(1000)

Your page body should now look like this (see HelloWorld/4-transition.html):

<body>
<svg id="chart" width="600" height="200"></svg>
<script>
const array = [100, 200, 300, 350, 375, 400, 500];

d3.select("#chart")
.selectAll("circle")
.data(array)
.enter()
.append("circle")
.attr("r", "10")
.attr("cy", 100)
.attr("cx", d => d)

setTimeout(function() {
d3.select("#chart").selectAll("circle")
.data([50, 75, 125, 225, 325, 425, 450])
.transition().duration(1000)
.attr("r", 5)
.attr("cx", d => d)
.style("fill", "red")
}, 2000)
</script>
</body>

Now, after two seconds, the dots will spend another second changing color, shrinking, and moving to the left. Congratulations! You created a full D3 application, complete with data updates and transitions.

Debugging D3

Although you don't need a full frontend modular development environment to create visualizations with D3.js, you still need a good debugger. Every browser comes with development tools that allow you to navigate a static page structure and generated DOM elements, and a console where you can interact in real time with the data used by the JavaScript engine in the real time.

The most important tool is the JavaScript console, where you will see any error messages. It's very common to get a blank page when you expected something else and to not have a clue on why your code doesn't work as expected. Sometimes it's just a comma you forgot, or the internet is down and some file was not loaded. If you have the JavaScript console open while you run your page, it will instantly tell you what's going on. It's also a good idea to use an editor with line numbering since most error messages inform the lines where the problem occurred:

Debugging JavaScript with the JavaScript console

You can open the developer tools as a frame in your browser or as a separate window. Following are the menu paths for the JavaScript console in latest versions of the three most popular browsers:

  • Chrome: View | Developer | JavaScript Console
  • Firefox: Tools | Web Developer | Web Console
  • Safari: Develop | Show Error Console

Many code fragments and examples can be tested by simply typing them in the JavaScript console. The console’s context is the currently loaded page. You will be able to access the functions of any JavaScript library file that was loaded with the <script> tag, and any global variables declared in <script></script> blocks, so you can also use the console to experiment with D3. The console is a great way to learn D3 since you can run functions in real time and immediately see the results they produce. You can try out many code examples in this book using the JavaScript console.

You have been reading a chapter from
Learn D3.js
Published in: May 2019
Publisher: Packt
ISBN-13: 9781838645571
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime