Empty Pipes

Selectable zoomable force directed graph in D3v4

  • 29 Apr 2017
  • |
  • javascript
  • d3.js
  • d3v4.js
  • |

A previous post described how to use d3.js to create a force-directed graph we can zoom in to and select nodes from. Such a tool is useful for displaying and arranging larger networks. My colleagues and I personally used it to create a small web application for displaying RNA secondary structure.

Since that post, a new version of D3 was released. D3 V4 introduced a lot of useful new features (see Irene Ros’s excellent overview of the differences between v3 and v4). Unfortunately, however, it did not maintain backward compatiblity with previous versions of d3. This means that the previous selectable zoomable force directed graph example could not be used with new code written with the latest version of the D3 library. Until now.

As in the previous example, this graph provides the following selection behavior:

  1. Clicking on a node selects it and de-selects everything else.
  2. Shift-clicking on a node toggles its selection status and leaves all other nodes as they are.
  3. Shift-dragging toggles the selection status of all nodes within the selection area.
  4. Dragging on a selected node drags all selected nodes.
  5. Dragging an unselected node selects and drags it while de-selecting everything else.

Upgrading the selectable zoomable force directed graph implementation to D3 v4 required a few minor and not-so-minor changes.

  "nodes": [
    {"id": "Myriel", "group": 1},
    {"id": "Napoleon", "group": 1},
    {"id": "Mlle.Baptistine", "group": 1},
  "links": [
    {"source": "Napoleon", "target": "Myriel", "value": 1},
    {"source": "Mlle.Baptistine", "target": "Myriel", "value": 8},

The source code for this example can be found as a github gist or on bl.ocks.org.