...

/

Path and Line Generator

Path and Line Generator

Get a brief introduction about paths and learn how to use a line generator to create different paths.

We'll cover the following...

Paths

Before we start drawing a line chart, let’s set a stage for it by exploring the path. A path is a graphical element of an SVG and is used to draw charts. A path is represented by the <path> tag. A path can be considered a combination of simple lines.

Let’s demonstrate a path in the following example.

Explanation

The explanation for the above code is simple and is as follows.

  • Lines 2-7: We have created an SVG canvas of size (500x500).
  • In line 8, we have defined the path using the d attribute, which specifies commands and numbers to initialize the path. The M command is the starting point of the path, which is (10,10). The L command means to draw a line from (10,10) to point (200, 200) and so on. We have then set the stroke of the path and width of the stroke using the attr() function.
  • The fill attribute is set to none, otherwise, we would get a region instead of the path.

We can draw complex paths using this method. But still, there is a need to have some magical function that will draw lines and paths on the basis of data so that we will not need to specify each point as we did in the previous example. Don’t worry, D3.js provides a line generator, which can help draw lines and paths based on the data more effectively.

Line Generator

A line generator that will take data as input and draw lines or paths based on the data.

d3.line()
  .x()
  .y()

d3.line() is an API used to generate lines. The two parameters x() and y() are used to specify the x and y position of the line for a given data point.

Let’s demonstrate how the line generator works through an example.

Explanation

See the following code to understand the working of the above code.

  • Lines 2-7: We have created an SVG canvas of size (500x500).
  • Lines 8-13: We have initialized the data, which will be used to draw a path.
  • We have defined a line generator, generator, with the help of d3.line().
  • Lines 14-16: The x(function (d) { return d.X; }) and y(function (d) { return d.Y; })) functions are used to define the x and y position of the line for a given data point where d designates the bound data and allows access to data.
  • The code from line 17 to line 22 will actually add a path using a line generator generator. We are using datum() instead of the data() function because we are only binding one path to all data elements instead of multiple paths for every single data element. In line 19, we have initialized the d attribute of the path, which will draw the path with the help of the line generator