Tree Diagram with D3.js

Tree diagrams are used for showing hierarchical relationships in data. This post will explain how to make a tree diagram using d3.js.

The Data

We are going to use a simple json file. Below is the code inside the json file.

{

"name": "President",

"children": [

{ "name": "VP of Academics",

"children":[

{"name":"Dean of Psych"},

{"name":"Dean of Ed"}

] },

{ "name": "VP of Finance" },

{ "name": "VP of Students" }

]

}

The code above is json file that models relationships among different positions you would find at a university. The root node is “president”. Under president, there are three children which are “VP of academics”, “VP of Finance”, and “VP of students”.

VP of academics also has two children which are “Dean of Psych” and “Dean of Ed.” You need to save this code on your computer somewhere as a json file for use in the d3.js code.

Below is a picture of what the final visual looks like.

1

The code is too long to post in its entirety here. Rather, you can download the code at the link here.

The code is explained below.

Code Description

Lines 1-26 setup the general documents, loads the data, adds an svg element to the body, and a g element to the svg element. Below is the code.

1.png

Lines 27-34 creates the actual tree and creates variables for the nodes and links that will be used later.

1.png

Lines 36-50 creates the diagonals and the nodes for the diagram. The diagonal is created using the .projection() method. Attributes are set for the diagonal as well under the .selectAll() method and includes the stroke color, width of the stroke, and the fill. The code is below.

1.png

Lines 52-66 create the circles for each node. This involves appending information in the element as well as setting colors for the circles.

1.png

Finally, lines 68-85 involve the text from the json file. The first method calls the text, the second method deals with position, and the last method also addresses position somewhat.

1

A lot of work but can be valuable in certain situations.

Conclusion

Making tree diagrams is another visualization available using d3.js. If the nature of the data is hierarchical this may be a useful approach to consider when make visualizations.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.