Reader small image

You're reading from  Data Visualization with D3.js Cookbook

Product typeBook
Published inOct 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781782162162
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Nick Zhu
Nick Zhu
author image
Nick Zhu

Nick Zhu is a professional programmer and data engineer with more than a decade experience in software development, big data, and machine learning. Currently, he is one of the founders and CTO of Yroo.com - meta search engine for online shopping. He is also the creator of dc.js—a popular multidimensional charting library built on D3.
Read more about Nick Zhu

Right arrow

Chapter 7. Getting into Shape

In this chapter we will cover:

  • Creating simple shapes

  • Using a line generator

  • Using line interpolation

  • Changing line tension

  • Using an area generator

  • Using area interpolation

  • Using an arc generator

  • Implementing arc transition

Introduction


Scalable Vector Graphics (SVG) is a mature World Wide Web Consortium (W3C) standard designed for user interactive graphics on the Web and Mobile platform. Similar to HTML, SVG can coexist happily with other technologies like CSS and JavaScript in modern browsers forming the backbone of many web applications. In today's Web, you can see use cases of SVG everywhere from digital map to data visualization. So far in this book we have covered most of the recipes using HTML elements alone, however, in real-world projects, SVG is the de facto standard for data visualization; it is also where D3's strength really shines. In this chapter, we will cover the basic concept of SVG as well as D3's support for SVG shape generation. SVG is a very rich topic. Volumes of books can be and have been devoted to this topic alone, hence, we are not planning or even going to try to cover all SVG-related topics, rather we'll focus on D3 and data visualization related techniques and features.

What is...

Creating simple shapes


In this recipe, we will explore a few simple built-in SVG shape formulae and their attributes. These simple shapes are quite easy to generate and are usually created manually using D3 when necessary. Though these simple shapes are not the most useful shape generator to know when working with D3, occasionally they could be handy when drawing peripheral shapes in your visualization project.

Getting Ready

Open your local copy of the following file in your web browser:

https://github.com/NickQiZhu/d3-cookbook/blob/master/src/chapter7/simple-shapes.html

How to do it...

In this recipe, we will draw four different shapes in four different colors using native SVG shape elements:

<script type="text/javascript">
    var width = 600,
        height = 500;
        
    var svg = d3.select("body").append("svg");
    
    svg.attr("height", height)
        .attr("width", width);    
        
    svg.append("line") // <-A
        .attr("x1", 0)
        .attr("y1", 200)
    ...

Using a line generator


D3 line generator is probably one of the most versatile generators. Though it is called a "line" generator, it has little to do with the svg:line element. In contrast, it is implemented using the svg:path element. Like svg:path, D3 line generator is so flexible that you can effectively draw any shape using line alone, however, to make your life easier, D3 also provides other more specialized shape generators, which will be covered in later recipes in this chapter. In this recipe, we will draw multiple data-driven lines using the d3.svg.line generator.

Getting Ready

Open your local copy of the following file in your web browser:

https://github.com/NickQiZhu/d3-cookbook/blob/master/src/chapter7/line.html

How to do it...

Now, let's see the line generator in action:

<script type="text/javascript">
    var width = 500,
        height = 500,
        margin = 50,
        x = d3.scale.linear() // <-A
            .domain([0, 10])
            .range([margin, width - margin...

Using line interpolation


By default, the D3 line generator uses linear interpolation mode, however, D3 supports a number of different line interpolation modes. Line interpolation determines how data points will be connected, for example, by a straight line (linear interpolation) or a curved line (cubic interpolation). In this recipe, we will show you how these interpolation modes can be set along with their effects.

Getting Ready

Open your local copy of the following file in your web browser:

https://github.com/NickQiZhu/d3-cookbook/blob/master/src/chapter7/line-interpolation.html

This recipe is built on top of what we have done in the previous recipe, so, if you are not yet familiar with basic line generator functions, please review the previous recipe first before proceeding.

How to do it...

Now, let's see how different line interpolation modes can be used:

    var width = 500,
        height = 500,
        margin = 30,
        x = d3.scale.linear()
            .domain([0, 10])
          ...

Changing line tension


If Cardinal interpolation mode (cardinal, cardinal-open, cardinal-closed) is used, then line can be further modified using tension settings. In this recipe, we will see how tension can be modified and its effect on line interpolation.

Getting Ready

Open your local copy of the following file in your web browser:

https://github.com/NickQiZhu/d3-cookbook/blob/master/src/chapter7/line-tension.html

How to do it...

Now, let's see how line tension can be changed and what effect it has on line generation:

<script type="text/javascript">
    var width = 500,
        height = 500,
        margin = 30,
        duration = 500,    
        x = d3.scale.linear()
            .domain([0, 10])
            .range([margin, width - margin]),
        y = d3.scale.linear()
            .domain([0, 1])
            .range([height - margin, margin]);
        
    var data = d3.range(10).map(function(i){
            return {x: i, y: (Math.sin(i * 3) + 1) / 2};
        });
    
    var svg ...

Using an area generator


Using D3 line generator, we can technically generate an outline of any shape, however, even with different interpolation-support, directly drawing an area using line (as in an area chart) is not an easy task. This is why D3 also provides a separate shape generator function specifically designed for drawing area.

Getting Ready

Open your local copy of the following file in your web browser:

https://github.com/NickQiZhu/d3-cookbook/blob/master/src/chapter7/area.html

How to do it...

In this recipe, we will add a filled area to a pseudo line chart effectively turning it into an area chart:

<script type="text/javascript">
    var width = 500,
        height = 500,
        margin = 30,
        duration = 500,
        x = d3.scale.linear() // <-A
            .domain([0, 10])
            .range([margin, width - margin]),
        y = d3.scale.linear()
            .domain([0, 10])
            .range([height - margin, margin]);
        
    var data = d3.range(11).map(function...

Using area interpolation


Similar to the D3 line generator, area generator also supports identical interpolation mode, hence, it can be used in combination with the line generator in every mode.

Getting Ready

Open your local copy of the following file in your web browser:

https://github.com/NickQiZhu/d3-cookbook/blob/master/src/chapter7/area-interpolation.html

How to do it...

In this recipe, we will show how interpolation mode can be configured on an area generator. This way matching interpolated area can then be created with corresponding line:

    var width = 500,
        height = 500,
        margin = 30,
        x = d3.scale.linear()
            .domain([0, 10])
            .range([margin, width - margin]),
        y = d3.scale.linear()
            .domain([0, 10])
            .range([height - margin, margin]);
        
    var data = d3.range(11).map(function(i){
        return {x: i, y: Math.sin(i)*3 + 5};
    });
        
    var svg = d3.select("body").append("svg");
        
    svg...

Using an arc generator


Among the most common shape generators—besides the line and area generator—D3 also provides the arc generator. At this point, you might be wondering, Didn't SVG standard already include circle element? Isn't that enough?

The simple answer to this is "no". The D3 arc generator is a lot more versatile than the simple svg:circle element. the D3 arc generator is capable of creating not only circles but also annulus (donut-like), circular sector, and annulus sector, all of which we will learn in this recipe. More importantly, an arc generator is designed to generate, as its name suggests, an arc (in others words, not a full circle or even a sector but rather arcs of arbitrary angle).

Getting Ready

Open your local copy of the following file in your web browser:

https://github.com/NickQiZhu/d3-cookbook/blob/master/src/chapter7/arc.html

How to do it...

In this recipe we will use arc generator to generate multi-slice circle, annulus (donut), circular sectors, and annulus sectors...

Implementing arc transition


One area where arc differs significantly from other shapes, such as line and area, is its transition. For most of the shapes we covered so far, including simple SVG built-in shapes, you can rely on D3 transition and interpolation to handle their animation. However, this is not the case when dealing with arc. We will explore the arc transition technique in this recipe.

Getting Ready

Open your local copy of the following file in your web browser:

https://github.com/NickQiZhu/d3-cookbook/blob/master/src/chapter7/arc-transition.html

How to do it...

In this recipe, we will animate a multi-slice annulus transitioning each slice starting from angle 0 to its final desired angle and eventually reaching a full annulus:

<script type="text/javascript">
var width = 400,
        height = 400,
        endAngle = 2 * Math.PI,
        colors = d3.scale.category20c();

var svg = d3.select("body").append("svg")
        .attr("class", "pie")
        .attr("height", height)
   ...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Data Visualization with D3.js Cookbook
Published in: Oct 2013Publisher: PacktISBN-13: 9781782162162
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

Author (1)

author image
Nick Zhu

Nick Zhu is a professional programmer and data engineer with more than a decade experience in software development, big data, and machine learning. Currently, he is one of the founders and CTO of Yroo.com - meta search engine for online shopping. He is also the creator of dc.js—a popular multidimensional charting library built on D3.
Read more about Nick Zhu