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 21, we have given the
nodesof thegraphto theforceSimulation()which will create an empty simulation with no force. - In line 22, we are creating a
forceusingd3.forceLink()on the basis of links between different nodes.d3.forceLink()receives an input oflinksin which thesourceandtargetnodes are specified. Then we specified theidto thenamewhich indicates thatsourceandtargetare specified on the basis ofnamein thenodes. - In line 24 and line 25, we have created two forces.
forceManyBodywill balance theforceLink()and will repel the nodes from each other and theforceCenterforce will be used to keepnodesat the center of the canvas. - Now if we look into the data shown on the
consolewe will see the positionxandyfor eachnode. And theirvxandvyvelocities, which are used in computing the forces, will be shown as well.
Note: It is necessary to specify
sourceandtargetin the data to draw the network.