How to create commonly used chart shapes such as multi-segment lines, areas, stacked bars, stacked areas, streamgraphs, pie segments and symbols using D3. Also covers rendering to canvas.
This chapter looks at the functions D3 provides for taking the effort out of drawing shapes such as lines:
pie chart segments:
The shapes in the above examples are made up of SVG
path elements. Each of them has a
d attribute (path data) which defines the shape of the path.
The path data consists of a list of commands such as
M0,80L100,100L200,30L300,50L400,40L500,80 which describe the shape of the path. Each letter such as
L describe a command such as ‘move to’ and ‘draw a line to’. See the SVG specification for more detail.
You can create path data yourself but D3 provides generator functions that do the work for you. These come in various forms:
|line||Generates path data for a multi-segment line (typically for line charts)|
|area||Generates path data for an area (typically for stacked line charts and streamgraphs)|
|stack||Generates stack data from multi-series data|
|arc||Generates path data for an arc (typically for pie charts)|
|pie||Generates pie angle data from array of data|
|symbol||Generates path data for symbols such as plus, star, diamond|
There’s also a generator for creating path data from GeoJSON. This is covered in the geographic section.
D3’s line generator produces a path data string given an array of co-ordinates.
You create a line generator using
d3.line() returns a function that accepts an array of co-ordinates and outputs a path data string.
Let’s define an array of co-ordinates:
lineGenerator with the array as the argument:
lineGenerator creates a string of
M (move to) and
L (line to) commands from the array of points.
You can use
pathData to set the
d attribute of a
.x and .y methods
By default each array element represents a co-ordinate defined by a 2-dimensional array (e.g.
[0, 100]). However you can specify how the line generator interprets each array element using the methods
For example suppose your data is an array of objects:
If you pass functions into the
.y methods of
lineGenerator D3 will apply these functions to each array element:
The x coordinate is set using a linear scale function applied to the array index. This results in equidistant points in the x direction. The y coodinate is set using a linear scale applied to the
The functions passed into the
.ymethods (and other similar methods) are known as accessor functions.
You can configure the behaviour when there’s missing data. Suppose your data has a gap in it:
the line generator will raise an error.
To overcome this you can use the
.defined method. You pass in a function that returns
true if the data is well defined. If the function returns
false the line generator will skip over it:
Now when you call
lineGenerator it leaves a gap in the line:
You can configure how the points are interpolated. For example you can interpolate each data point with a B-spline:
Although there’s a multitude of different curve types available they can be divided into two camps: those which pass through the points (
curveStep) and those that don’t (
See the curve explorer for more information.
Rendering to canvas
By default the shape generators output SVG path data. However they can be configured to draw to a canvas element using the
The radial line generator is similar to the line generator but the points are transformed by angle (working clockwise from 12 o’clock) and radius, rather than
radialLine generator also has methods
.radius into which you can pass accessor functions. These are handy if you’ve an array of objects:
The area generator outputs path data that defines an area between two lines. By default it generates the area between
y=0 and a multi-segment line defined by an array of points:
You can configure the baseline using the
You can also pass accessor functions into the
.y0defines the baseline and
.y1the top line.
As with the line generator you can specify the way in which the points are interpolated using
.curve(), handle missing data using
.defined() and render to canvas using
The radial area generator is similar to the area generator but the points are transformed by angle (working clockwise from 12 o’clock) and radius, rather than
The stack generator takes an array of objects and generates an array for each object property. Each array contains lower and upper values for each data point. The lower and upper values are computed so that each series is stacked on top of the previous series.
In this example we’ve an array of objects. We create a stack generator using
d3.stack. We use its
.keys method to pass in the property keys which we’d like to stack. In this case we’re stacking
The data output by the stack generator can be used however you like, but typically it’ll be used to produce stacked bar charts:
or when used in conjunction with the area generator, stacked line charts:
The order of the stacked series can be configured using
Each series is summed and then sorted according to the chosen order. The possible orders are:
|stackOrderNone||(Default) Series in same order as specified in .keys()|
|stackOrderAscending||Smallest series at the bottom|
|stackOrderDescending||Largest series at the bottom|
|stackOrderInsideOut||Largest series in the middle|
|stackOrderReverse||Reverse of stackOrderNone|
By default the stacked series have a baseline of zero. However you can configure the offset of the stack generator to achieve different effects. For example you can normalise the stacked series so that they fill the same height:
The available offsets are:
|stackOffsetNone||(Default) No offset|
|stackOffsetExpand||Sum of series is normalised (to a value of 1)|
|stackOffsetSilhouette||Center of stacks is at y=0|
|stackOffsetWiggle||Wiggle of layers is minimised (typically used for streamgraphs)|
Here’s a streamgraph example using
Arc generators produce path data from angle and radius values. An arc generator is created using:
It can then be passed an object containing
outerRadius properties to produce the path data:
endAngleare measured clockwise from the 12 o’clock in radians.
You can configure
endAngle so that you don’t have to pass them in each time:
You can also configure corner radius (
cornerRadius) and the padding between arc segments (
Arc padding takes two parameters
padRadius which when multiplied together define the distance between adjacent segments. Thus in the example above, the padding distance is
0.02 * 100 = 2. Note that the padding is calculated to maintain (where possible) parallel segment boundaries.
You might ask why there isn't a single parameter padDistance for defining the padding distance. It's split into two parameters so that the pie generator (see later) doesn't need to concern itself with radius.
You can define accessor functions for
outerRadius. For example:
It’s sometimes useful to calculate the centroid of an arc, such as when positioning labels, and D3 has a function
.centroid() for doing this:
Here’s an example where
.centroid() is used to compute the label positions:
The pie generator goes hand in hand with the arc generator. Given an array of data, the pie generator will output an array of objects containing the original data augmented by start and end angles:
You can then use an arc generator to create the path strings:
Notice that the output of
pieGenerator contains the properties
endAngle. These are the same properties required by
The pie generator has a number of configuration functions including
.padAngle() specifies an angular padding (in radians) between neighbouring segments.
.endAngle() configure the start and end angle of the pie chart. This allows, for example, the creation of semi-circular pie charts:
By default the segment start and end angles are specified such that the segments are in descending order. However we can change the sort order using
The symbol generator produces path data for symbols commonly used in data visualisation:
You can use
pathData to define the
d attribute of a path element:
Here’s a simple chart using the symbol generator:
D3 provides a number of symbol types: