Recently, I have been involved in a number of projects that have required the use for neat interactive vizualization of networks. After strying out a few options, D3 quickly came out as the most logical and appealling choice. To paraphrase D3's home website *D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS*. While D3 can be a tad wordy, and may have a realtively steep learning curve at the start, it becomes a dream to work with once you familiarize with it. If you run into a hurdle (and we always do), D3 has a vibrant community of users that have generously shared their knowledge (especially on StackOverflow). I feel like I have abused this generosity, so I figured I would try and share some snippets of the knowledge that I have accumulated during my short time with D3. For most of this post, I will be working with the standard miserables dataset.
A basic D3 force-directed network
For the sake of clarity, I wil omit the usual HTML wrappers, and get straight to the meaty D3 bit! First and foremost, we need to make sure we include the d3.js library:
We can also add some CSS styling to the nodes and links that will be displayed in our network and finally display the most basic D3 force directed network:
See the Pen XbMpGq by Thomas Vincent (@tlfvincent) on CodePen.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
stroke-opacity: .6;
}
.node text {
font: 9px helvetica;
}
d3-tip {
line-height: 1;
color: black;
}
</style>
Adding text labels to nodes
Usually, it is desirable to display attributes on the nodes, so people often like to add text information. This can be achieved by adding a few changes to the code shown above. Below is the new code chunk that needs to be modified:
See the Pen zGZZGJ by Thomas Vincent (@tlfvincent) on CodePen.
We can also add some styling to the displayed text by adding the following CSS:
1
2
3
.node text {
font: 9px helvetica;
}
Obviously, a network with too many nodes becomes quickly unreadable once we add labels, so in this case it is preferable to resort to D3's tooltip functionnality, which allows us to display the desired properties whenever a user hovers over any given node.
Adding a hover functionality
In order to enable hovering over the nodes in your network, it is first necssary to sort the relevant javascript code.
As usual, one can also add some CSS styling to the hover tip tool.
1
2
3
4
d3-tip {
line-height: 1;
color: black;
}
See the Pen yNMjrQ by Thomas Vincent (@tlfvincent) on CodePen.
Adding FontAwesome icons instead of nodes
FontAwesome icons and associated CSS codes can be found here
Other helpful pages
- This page gives a number of additional features that range in increasing degree in complexity.
- This page shows a really neat example of convex hulls applied to clusters of nodes in a D3 network.