Introduction to Nodes and Links
Get yourself familiar with the very important concept of nodes and links.
We'll cover the following
Introduction
After exploring different charts in the previous lesson, let’s explore different visualization tools. There are some types of data that are hard to show through charts. Let’s say we have data where we want to represent the connections between different cities. That’s where we will use nodes and links to show the network.
In the above illustration, nodes represent the cities, and links are used to join these cities.
Network layout
Before drawing the network, let’s explore the basics of a network. To draw a network of nodes and links, we need to know the position of the nodes for the given data. As we needed an angle generator to add angle information to the data in the pie chart, we need the positional information to draw the nodes and links of the network. D3.js provides the d3.forceSimulation()
API to add positional information to nodes. It creates a dynamic simulation in which nodes are organized in an optimal way based on our constraints.
d3.forceSimulation()
uses forces for positioning different visual elements. Forces can be set up between elements, for example:
- All elements repel one another (
forceManyBody()
) - Elements are attracted to the center(s) of gravity (
forceCenter()
)
In the following example, we will add positional information to the data with the help of the d3.forceSimulation()
API.
Explanation
As shown in the above code:
- In line 20, we have given the
nodes
of thegraph
to theforceSimulation()
which will create an empty simulation with no force. - In line 21, we are creating a
force
usingd3.forceLink()
on the basis of links between different nodes.d3.forceLink()
receives an input oflinks
in which thesource
andtarget
nodes are specified. Then we specified theid
to thename
which indicates thatsource
andtarget
are specified on the basis ofname
in thenodes
. - In line 23 and line 24, we have created two forces.
forceManyBody
will balance theforceLink()
and will repel the nodes from each other and theforceCenter
force will be used to keepnodes
at the center of the canvas. - Now if we look into the data shown on the
console
we will see the positionx
andy
for eachnode
. And theirvx
andvy
velocities, which are used in computing the forces, will be shown as well.
Note: It is necessary to specify
source
andtarget
in the data to draw the network.