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.
- Line 1-6: We have created an SVG canvas of size (500x500).
- In line 7, we have defined the path using the
d
attribute, which specifies commands and numbers to initialize the path. TheM
command is the starting point of the path, which is(10,10)
. TheL
command means to draw a line from(10,10)
to point(200, 200)
and so on. We have then set thestroke
of the path andwidth
of the stroke using theattr()
function. - The
fill
attribute is set tonone
, 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.
- Line 1-6: We have created an SVG canvas of size (500x500).
- Line 7-12: We have initialized the data, which will be used to draw a path.
- We have defined a line generator,
generator
, with the help ofd3.line()
. - Line 13-15: The
x(function (d) { return d.X; })
andy(function (d) { return d.Y; }))
functions are used to define the x and y position of the line for a given data point whered
designates the bound data and allows access to data. - The code from line 16 to line 21 will actually add a
path
using a line generatorgenerator.
We are usingdatum()
instead of thedata()
function because we are only binding onepath
to all data elements instead of multiplepath
s for every single data element. In line 18, we have initialized thed
attribute of the path, which will draw the path with the help of the line generator