Line Generator

A line generator is a function for generating the coordinates required for drawing a line with a dataset.

We are going to draw the line for our line chart. We need a way to calculate the coordinates for the points in the line. Then, we need to connect the points. We have years worth of data. There is a lot of points that need to be drawn. D3 comes with something it calls generators.

What are generators?

In D3, generators are functions that can generate a path. The value produced by a generator can be used with the d attribute of the <path> element. The <path> element is our best bet for drawing a line chart because of how many points will need to be drawn. There is not another shape available that can accomplish our needs for drawing a line chart.

However, the <path> element is a very complex shape to work with, so D3 introduces generators to make it easy for working with the path shape. There is a generator for producing a line. Let’s look at how we can use this generator to help us draw our line chart.

D3 shape

There is a package called D3 shape. You can find it here:

This package comes bundled with the core of D3. We do not need to do anything to make it included with D3. This package comes with a list of generators for drawing different kinds of shapes. If we scroll down to the description, we will find the following:

Visualizations typically consist of discrete graphical marks, such as symbols, arcs, lines, and areas. While the rectangles of a bar chart may be easy enough to generate directly using SVG or Canvas, other shapes are complex, such as rounded annular sectors. This module provides a variety of shape generators for your convenience.

As the description states, the purpose of this package is to help draw complex shapes. If we were to go through the documentation, we would find that this package can help us draw things like lines, pies, arcs, curves, and areas. We will be exploring some of the generators throughout this section.

Creating a generator

Let’s get started. We are going to continue working on the script. We left off with preparing the scales. The next step is to prepare the generator. We are not going to draw the line yet because we do not know how to draw it. We will need D3’s help. Therefore, we are going to define the generators after defining the scales.

Create a variable called lineGenerator. Its value will be the d3.line() function.

Get hands-on with 1200+ tech skills courses.