Book Image

D3.js 4.x Data Visualization - Third Edition

By : Aendrew Rininsland, Swizec Teller
Book Image

D3.js 4.x Data Visualization - Third Edition

By: Aendrew Rininsland, Swizec Teller

Overview of this book

Want to get started with impressive interactive visualizations and implement them in your daily tasks? This book offers the perfect solution-D3.js. It has emerged as the most popular tool for data visualization. This book will teach you how to implement the features of the latest version of D3 while writing JavaScript using the newest tools and technique You will start by setting up the D3 environment and making your first basic bar chart. You will then build stunning SVG and Canvas-based data visualizations while writing testable, extensible code,as accurate and informative as it is visually stimulating. Step-by-step examples walk you through creating, integrating, and debugging different types of visualization and will have you building basic visualizations (such as bar, line, and scatter graphs) in no time. By the end of this book, you will have mastered the techniques necessary to successfully visualize data and will be ready to use D3 to transform any data into an engaging and sophisticated visualization.
Table of Contents (18 chapters)
Title Page
Credits
About the Authors
About the Author2
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
3
Shape Primitives of D3

Getting started with Node and Git on the command line


I will try not to be too opinionated in this book about which editor or operating system you should use to work through it (though I am using Atom on macOS X), but you will need a few prerequisites to start.

The first is Node.js. Node is widely used for Web development nowadays, and it's actually just JavaScript that can be run on the command line. Later on, in this book, I'll show you how to write a server application in Node, but for now, let's just concentrate on getting it and npm (the brilliant and amazing package manager that Node uses) installed. If you're on Windows or macOS X without Homebrew, use the installer at https://nodejs.org/en/. If you're on macOS X and are using Homebrew, I would recommend installing n instead, which allows you to easily switch between versions of Node:

$ brew install n
$ n lts

Note

If you're in Windows, the $ above might be confusing. In UNIX-based operating systems, regular users see a $ on the command prompt, and the root administrator user sees a #. By indicating that, I mean that you should run the above commands as a regular user and not a super-user.

Regardless of how you do it, when you have finished, verify by running the following lines:

$ node --version
$ npm --version

If it displays the versions of node and npm, it means you're good to go.

Note

I'm using 6.5.0 and 3.10.3, respectively, though yours might be slightly different--the key is making sure that node is at least version 6.0.0.

If it says something similar to Command not found, double-check whether you've installed everything correctly, and verify that Node.js is in your $PATH environment variable.

Throughout this book, we will use a combination of Babel and Webpack to turn our fancy modular modern JavaScript into something even the crummiest old browsers (Hi, Internet Explorer 9!) can run.

First, create a package.json file to store the version of each dependency that we want. Do this by first creating a new folder and then running npm init:

$ mkdir d3-projects
$ cd d3-projects
$ npm init -y

The -y flag tells npm init to use all the default settings and not ask you any questions.  Next, install our stack, using npm:

$ npm install "babel-core@^6" "babel-loader@^6" "babel-preset-es2017@^6" "babel-preset-stage-0@^6" "webpack@^2" "webpack-dev-server@^2" css-loader style-loader json-loader --save-dev

This installs v2 of Webpack, v6 of Babel, and a boatload of presets and plugins for both. It then saves these to package.json so that you can reinstall them as easily as running:

$ npm install

You'll also need to install D3 by typing the following command:

$ npm install d3 --save

Next, we need to create a configuration for Webpack. I won't get into detail around what each of the directives do; for that, look at the config supplied with the book repository; save this as webpack.config.js:

const path = require('path');
module.exports = [{
  entry: {
    app: ['./lib/main.js'],
  },
  output: {
    path: path.resolve(__dirname, 'build'),
    publicPath: '/assets/',
    filename: 'bundle.js',
  },
  devtool: 'inline-source-map',
  module: {
    rules: [{
      test: /.js?$/,
      exclude: /(node_modules|bower_components)/,
      loader: 'babel-loader',
    }, {
      test: /.json$/,
      loader: 'json-loader',
    }, {
      test: /.css$/,
      loader: 'style-loader!css-loader',
    }],
  },
}];

 

Lastly, we need to edit package.json to have a few shortcuts to make our lives easier. After the line that starts with name, put the following:

"babel": {
  "presets": [
    "es2017"
  ]
},
"main": "lib/main.js",
"scripts": {
  "start": "webpack-dev-server --inline",
},

This is what you need to do if you're starting a project from scratch.

Alternatively, you can clone the book's repository from GitHub. GitHub is where most of the world stores open source and other code. I've done a lot of configuration for you, in addition to supplying all of the examples and sample data. I'll move forward under the assumption you've cloned the book repository and are working out of the book repository directory. To do this, run the following command:

$ git clone https://github.com/aendrew/learning-d3-v4
$ cd learning-d3-v4

This will clone the development environment and all the samples in the learning-d3-v4/ directory, as well as switching you into it and installing all of the dependencies via npm.

Note

Another option is to fork the repository on GitHub and then clone your fork instead of mine as was just shown in the preceding code. This will allow you to easily publish your work on the cloud, enabling you to more readily seek support, display finished projects on GitHub Pages, and even submit suggestions and amendments to the parent project. This will help us improve this book for future editions. To do this, fork aendrew/learning-d3-v4 by clicking the "fork" button in GitHub, and replace aendrew in the preceding code snippet with your GitHub username.

Each chapter of this book is in a separate branch. To switch between them, type the following command:

$ git checkout chapter1

 

Replace 1 with whichever chapter you want the examples for. Stay on the master branch for now, though. To get back to it, type this line:

$ git stash save && git checkout master

The master branch is where you'll do a lot of your coding as you work through this book.  We still need to install our dependencies, so let's do that now:

$ npm install

All of the source code that you'll be working on is in the lib/ folder. You'll notice it contains just a main.js file; almost always, we'll be working in main.js, as index.html is just a minimal container to display our work in. This is it in its entirety, and it's the last time we'll look at any HTML in this book:

<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8">
 <title>Learning Data Visualization with D3.js</title>
 </head>
 <body>
 <script src="assets/bundle.js"></script>
 </body>
</html>

There's also an empty style sheet in styles/index.css, which we'll add to in a bit.

Next, start the development server by typing the following line:

$ npm start

This starts up the Webpack development server, which will transform our new-fangled ES2017 JavaScript into backward-compatible ES5 and serve it to the browser. Now, point Chrome (or whatever, I'm not fussy--so long as it's not Internet Explorer!) to localhost:8080 and fire up the developer console (CtrlShift + J for Linux and Windows and Option + Command + J for Mac). You should see a blank website and a blank JavaScript console with a Command Prompt waiting for some code: