Reader small image

You're reading from  D3.js 4.x Data Visualization - Third Edition

Product typeBook
Published inApr 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781787120358
Edition3rd Edition
Languages
Tools
Right arrow
Authors (2):
Aendrew Rininsland
Aendrew Rininsland
author image
Aendrew Rininsland

<p>Aendrew Rininsland is a developer and journalist who has spent much of the last half a decade building interactive content for newspapers such as The Financial Times, The Times, Sunday Times, The Economist, and The Guardian. During his 3 years at The Times and Sunday Times, he worked on all kinds of editorial projects, ranging from obituaries of figures such as Nelson Mandela to high-profile, data-driven investigations such as The Doping Scandal the largest leak of sporting blood test data in history. He is currently a senior developer with the interactive graphics team at the Financial Times.</p>
Read more about Aendrew Rininsland

Swizec Teller
Swizec Teller
author image
Swizec Teller

Swizec Teller is a geek with a hat. Founding his first startup at 21, he is now looking for the next big idea as a full-stack web generalist focusing on freelancing for early-stage startup companies. When he isn't coding, he's usually blogging, writing books, or giving talks at various non-conference events in Slovenia and nearby countries. He is still looking for a chance to speak at a big international conference. In November 2012, he started writing Why Programmers Work at Night, and set out on a quest to improve the lives of developers everywhere.
Read more about Swizec Teller

View More author details
Right arrow

Chapter 7. The Other Layouts

In the preceding chapter, we used the hierarchical layouts in d3-hierarchy to create a nice selection of charts. In this chapter, we will look at other layouts in D3 v4, which are spread across a few different modules. Instead of calling them normal or nonhierarchical layouts, let's just call them the other layouts because there's not a lot of similarities between them.

Hoorah for modular code


Let's get to it. Go to lib/main.js and add the following line to the imports section:

import westerosChart from './chapter7/index';

Create a folder called chapter7 and create a file called index.js. Add the following code to it:

import * as d3 from 'd3'; 
import * as legend from 'd3-svg-legend'; 
import baseChart from '../chapter6/'; 
import './chapter7.css'; 
import { 
  colorScale as color, 
  tooltip, 
  connectionMatrix, 
  uniques, 
} from '../common';

We import our westerosChart object from the last chapter as baseChart, so we can just extend it here.

That's all there is to it; we're ready for our first chart.

When the moon hits your eye (chart), like a big pizza pie (chart)


Pie charts are a very common way of presenting simple quantitative data, but they have their own limitations--people have greater difficulty perceiving the size of an area when it's in a circular shape, and you really need to make sure that the wedges are ordered descending clockwise from the top in order to be able to adequately compare them. That said, they're common enough that knowing how to make them is an incredibly useful skill as anyone doing data visualization work will at some point be asked for one.

D3's pie chart layout resides in the d3-shape package and is somewhere between the layouts of the last chapter and the line generators of Chapter 3, Shape Primitives of D3. We create a pie chart layout and pass it an array of numbers and then pass that to an arc generator to create our pie chart. Let's get to it.

We start by filtering out people who have less than 60 minutes of screen time and creating a pie generator...

Histograms, Herstograms, Yourstograms, and Mystograms


Another simple layout is the histogram, which simplifies creating bar charts when they're in a continuous series. We can also use it for binning a series of values so that we don't have to do as many gymnastics with Array.prototype.reduce and Array.prototype.map.

In this instance, we will create an ordinal scale of episodes and seasons and use that to create a histogram. In doing so, we're going to use a new dataset, which I've included in the data/ directory, GoT-deaths-by-season.json. This includes all the deaths in the show in the following format:

    { 
      "name": "Will", 
      "role": "Ranger of the Night's Watch", 
      "death": { 
        "season": 1, 
        "episode": 1 
      }, 
      "execution": "Beheaded for desertion by Ned Stark", 
      "likelihoodOfReturn": "0%" 
    },

The only data we're really concerned with here is the death object, which we'll use to create an ordinal scale.

Start by resetting main.js by commenting...

Striking a chord


The chord layout creates a circular diagram showing relations in a dataset. We will use yet another dataset here, found in the data/ directory stormofswords.csv, from the Network of Thrones dataset available at https://www.macalester.edu/~abeverid/thrones.html.

This dataset was created by looking at the proximity of character names in the text of the book series in order to find the weight of each character's connection to the other characters. It is an ideal dataset for the next two examples, which look at arbitrary nonhierarchical connections between data.

Start by doing the comment out the last example and add this dance in main.js:

westerosChart.init('chord', 'data/stormofswords.csv');

Go back to chapter7/index and scaffold out the new chart method:

westerosChart.chord = function Chord(_data) {};

Nothing new. We will create an array of sources and links between them, assuming the strength of the connection is greater than 20. Add this to the Chord function:

  const minimumWeight...

May the force (simulation) be with you


One of the cooler layouts provided by D3 (in the d3-force package) is force simulation. This is actually really useful, as it allows us to position elements on the screen using simulated physical properties. This can be really useful when the positioning of an element doesn't have anything to do with its data, such as in a network diagram, where the linkages between items is more important than when they are on screen.

We will use the network dataset from the last example to create a network of connections in the show. Go to main.js, comment out the last example, and add this line:

westerosChart.init('force', 'data/stormofswords.csv');

Go back to chapter7/index and add a new function enclosure:

westerosChart.force = function Force(_data) { 
  const nodes = uniques( 
    _data.map(d => d.Target)
      .concat(_data.map(d => d.Source)), 
    d => d) 
     .map(d => 
     ({ id: d, total: _data.filter(e => e.Source === d).length })); 

  fixateColors...

Got mad stacks


The stack layout allows us to stack regions in a chart, which is useful for things such as stacked area charts and what have you. It's in the d3-shape package.

Go back to main.js and comment out the last example and add the following:

westerosChart.init('stack',
  'data/GoT-deaths-by-season.json', false);

We add another option to this because we're going to create two charts from this example. This time we're using our deaths-by-season dataset.

Inchapter7/index.js add the following to the bottom of the file:

westerosChart.stack = function Stack({ data }, isStream = false) { 
  const episodesPerSeason = 10; 
  const totalSeasons = 6; 
  // Create a nest containing deaths per episode
  const seasons = d3.nest() 
    .key(d => d.death.episode) 
    .key(d => d.death.season) 
    .entries(data.filter(d => !d.death.isFlashback)) 
    .map(v => { 
      return d3.range(1, totalSeasons + 1)
        .reduce((item, episodeNumber) => { 
          const deaths = v.values.filter...

Bonus chart - Streamalicious!


Our bonus chart in this chapter is easy; we've already made it!

Go back to main.js, comment out the last line, and add this one:

westerosChart.init('stack',
    'data/GoT-deaths-by-season.json', true);

All we've done is pass true. This gives us a stream chart, because we set the offset in the last example to d3.stackOffsetWiggle. Kind of cool looking, huh?

Summary


That's pretty much all the layouts, and we've done a pretty decent dip into each of them. I've provided the package names for each so that you can peruse the documentation. Each has a lot of options you can tweak, which is helpful for producing a very wide array of charts.

After going full out with these examples, we used almost every trick we've learned so far. We even wrote so much code that we pretty much have our own utility library! With a bit of generalization, some of those functions could be layouts of their own. There's a whole world of community that developed layouts for various types of charts. The d3-plugins repository on GitHub (https://github.com/d3/d3-plugins) is a good way to start exploring.

You now understand what all the default layouts are up to, and I hope you're already thinking about using them for purposes beyond the original developers' wildest dreams.

In the next chapter, you'll learn how to use D3 outside of the browser--that's right folks, we're headed to...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
D3.js 4.x Data Visualization - Third Edition
Published in: Apr 2017Publisher: PacktISBN-13: 9781787120358
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.
undefined
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 $15.99/month. Cancel anytime

Authors (2)

author image
Aendrew Rininsland

<p>Aendrew Rininsland is a developer and journalist who has spent much of the last half a decade building interactive content for newspapers such as The Financial Times, The Times, Sunday Times, The Economist, and The Guardian. During his 3 years at The Times and Sunday Times, he worked on all kinds of editorial projects, ranging from obituaries of figures such as Nelson Mandela to high-profile, data-driven investigations such as The Doping Scandal the largest leak of sporting blood test data in history. He is currently a senior developer with the interactive graphics team at the Financial Times.</p>
Read more about Aendrew Rininsland

author image
Swizec Teller

Swizec Teller is a geek with a hat. Founding his first startup at 21, he is now looking for the next big idea as a full-stack web generalist focusing on freelancing for early-stage startup companies. When he isn't coding, he's usually blogging, writing books, or giving talks at various non-conference events in Slovenia and nearby countries. He is still looking for a chance to speak at a big international conference. In November 2012, he started writing Why Programmers Work at Night, and set out on a quest to improve the lives of developers everywhere.
Read more about Swizec Teller