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
About the Authors
About the Author2
About the Reviewer
Customer Feedback
Shape Primitives of D3

Tree the whales!

Let's start with the most basic of hierarchical charts -- a tree! Create a new function and fill it with the following:

westerosChart.tree = function Tree(_data) { 
  const data = getMajorHouses(_data); 
  const chart = this.container; 
  const stratify = d3.stratify() 
    .parentId(d => d.fatherLabel) 
    .id(d => d.itemLabel); 
  const root = stratify(data); 
  const layout = d3.tree() 

We use our next-to-be-written getMajorHouses() function to filter out characters who don't have a fatherLabel property and whose itemLabel isn't set as anybody's fatherLabel property. We then create a new stratify object and set its parentId() accessor function to each item's fatherLabel and the id() accessor to each item's itemLabel. We're able to do the latter with this dataset because we know that each itemLabel is distinct; if this was not the case (for instance, if you had a dataset where there were a few...