Force-directed Network diagram with React and D3.js

Dataviz logo representing a Network chart.

This tutorial is a variation around the general introduction to network diagram with react and d3.js. You should probably understand the concepts described there before reading here, notably everything related to the d3-force plugin.

This example shows how to apply the concepts of the general tutorial to a real dataset. It creates a force-directed graph that describes the network of character co-occurrence in Les Misérables.

A code sandbox is provided for the final result, but explanations target what's different compared to a classic network diagram.

Useful links

Plot and code

If you are in a hurry, here is the final plot we're trying to achieve here, together with its code:🙇‍♂️

In this network diagram, each node is a character of the book Les Misérables. The network chart tries to localise characters who often appear together close to each other.

The dataset comes from this Observable version that uses d3.js only.

Network section

A network diagram made with d3.js and react. It shows the character co-occurence in Les Misérables.

Color Palette

The only difference with the very simple network chart of the mainnetwork tutorial is the presence of a color palette used to color the nodes.

Each node of the dataset is attributed to a group. It is thus possible to create a color scale using a scaleOrdinal:

// List of Groups
const allGroups = [...new Set(nodes.map((d) => d.group))];

// Color scale
const colorScale = scaleOrdinal()
  .domain(allGroups)
  .range(schemeCategory10);

Here I am using the schemeCategory10 color scale to avoid defining those color by hand.

Once the color scale is ready, it is straightforward to call it for each node in the drawNetwork() function.

Flow

Contact

👋 Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❤️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!