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.

Console
forceSimulation code

Explanation

As shown in the above code:

  • In line 20, we have given the nodes of the graph to the forceSimulation() which will create an empty simulation with no force.
  • In line 21, we are creating a force using d3.forceLink() on the basis of links between different nodes. d3.forceLink() receives an input of links in which the source and target nodes are specified. Then we specified the id to the name which indicates that source and target are specified on the basis of name in the nodes.
  • In line 23 and line 24, we have created two forces. forceManyBody will balance the forceLink() and will repel the nodes from each other and the forceCenter force will be used to keep nodes at the center of the canvas.
  • Now if we look into the data shown on the console we will see the position x and y for each node. And their vx and vy velocities, which are used in computing the forces, will be shown as well.

Note: It is necessary to specify source and target in the data to draw the network.