Plotting trees recursively

The idea for this visualization is something I have been thinking about for quite some time now. Although it is not this specific visualization per se, but the idea of visualizing a nested tree in an appealing way. This method is actually quite easy to implement, and HTML and CSS are doing all the heavy lifting of displaying something that actually looks nice. The illustration below is an example of what the final result will look like, and the rest of this post is about developing the visualization.

A data structure for trees

The first thing that we will need is a data structure that can model trees. We can do this by creating a class Node, and giving that class a property children: Node[] in which we collect a bunch of other nodes. If we do this recursively, then we have a tree. We will also add a name: string property, which we will use to give a name to the node. Finally, we add a addNode(name: string) function to the class, which we use to easily add a new node under an existing node. All in all, this results in the following code:

class Node {
    name = "Untitled node";
    children = [];
    
    constructor(name) {
        this.name = name;
    }

    addNode(name) {
        const node = new Node(name);
        this.children.push(node);
        return node;
    }
}

Generating the plot recursively

The next thing that we will do is write a class that will generate the HTML of a tree. The idea is to alternate between have a horizontal and a vertical layout. We will start with a horizontal layout, which is for the first node. Then the second layer of the tree is layed out vertically. The third layer is horizontal again, and so on. This is done with the flex-direction property of CSS.

Direction = { 
    Horizontal: "flex-row",
    Vertical: "flex-col"
}

The next thing we will do is define a class RecursivePlot that will generate the HTML elements for the plot. This class has a constructor with a elementId: string argument, which is the ID of the element in which we want to add the generated HTML. This class also has a method draw(node: Node) which we will use to generate the HTML.

In this function we will define another function __draw(node: Node, element: HTMLElement, direction: Direction) which is called recursively to generate the HTML element for the entire tree. The HTML that we will generate is simply a div and a class .node which we'll use for styling. We will also set the flex-direction property alternating between row and column.

Once we have the __draw function defined, we will create a div for the root node. We will also add the .node class to this element. We will then call __draw, and pass in the root node, the element of the root node, and the direction for flexbox. If we combine all of this, we get the following class:

class RecursivePlot {
    constructor(elementId) {
        this.element = document.getElementById(elementId);
    }

    draw(node) {
        const __draw = (node, element, direction) => {
            // Alternate between the direction.
            direction = direction == Direction.Horizontal
                ? Direction.Vertical
                : Direction.Horizontal;

            // Create a div for each child node, and recursively call
            // this function.
            for (let child of node.children) {
                const div = document.createElement('div');
                div.classList.add('node');
                div.classList.add(direction);
                element.appendChild(div);
                __draw(child, div, direction);
            }

            // Create a label for the name of the node.
            const label = document.createElement('div');
            label.classList.add('label');
            element.appendChild(label);
            label.innerHTML = node.name;

            // If the node doesn't have any children, indicate
            // that this node is a leaf.
            if (node.children.length == 0) {
                label.classList.add('node-leaf');
            }
        }

        // Default direction to start with (sets flex-direction).
        const defaultDirection = Direction.Vertical;

        // Create the container for the root node.
        const container = document.createElement('div');
        container.classList.add('node');
        container.classList.add(defaultDirection);
        this.element.appendChild(container);

        __draw(node, container, defaultDirection);
    }
}

Styling the recursive tree plot

Now that we have a method to generate the HTML elements, we need to style them. We will start with adding a few utility classes for flex-direction. Note that these class names are also defined in the Direction enum.

.flex-row {
    flex-direction: row;
}

.flex-col {
    flex-direction: column;
}

With that out of the way, we are going to style the node itself. We want to set the display mode to display: inline-flex, because we want the plot to be as small as possible and only grow bigger if there is more content in it. You could also have the plot fill the entire container by setting it to display: flex. We also set flex-wrap: wrap in the case we have a lot of elements and flex-grow: 1 so that the elements fill the entire container. The position should be set to position: relative, because we will need this to show the labels in the correct position. So far this gives us the following:

.node {
    display: inline-flex;
    position: relative;
    overflow: hidden;
    flex-wrap: wrap;
    flex-grow: 1;
    ...
}

To let the nodes have some space around it we will set padding: 8px and gap: 8px. On the top of the node we reserve some space for the label by setting padding-top: 22px. The background color of the node is a white transparent color with an opacity of $33\%$, giving background-color: rgba(255, 255, 255, 0.33). This gives a nice effect when we are stacking nodes on top of each other. To give the illusion of depth, we will add two different box-shadow's. The idea is to imagine that there is a light on the top of the page, and we are rendering the resulting shadow. A second shadow gives a more realistic look. To ensure the label is visible we set min-width: 40px. We will also add border-radius: 4px to smooth the corners, but this is a personal preference. Finally we set the font size font-size: 90%. Note that the $90\%$ is applied consecutively as we nest more nodes. This ensures that the font size of the label is getting smaller and smaller.

.node {
    ...
    gap: 8px;
    padding: 8px;
    padding-top: 22px;
    background-color: rgba(255, 255, 255, 0.33);
    box-shadow: 0 0 4px rgba(0, 0, 0, 0.05), 0 2px 4px rgba(0, 0, 0, 0.1);
    min-width: 40px;
    border-radius: 4px;
    font-size: 90%;
}

Because the nodes in the plot are set to display: inline (by setting display: inline-flex), we also want to center the content of the plot. This ensures that the plot is always centered in the container that it is rendered in.

.plot {
    text-align: center;
}

We also want to set the box-sizing: border-box, because this fixes the weird sizing when applying padding. Actually, this should have been the default value in browsers anyway, but sadly it's not.

.plot * {
    box-sizing: border-box;
}

Because we can have a white background, which doesn't work well with the transparent background, we also want to set a background for the first node.

.plot > .node {
    background-color: #aaa;
}

Finally, we will put the label in the correct position. We have already added some extra padding to the top of the node, which we will now use to position the label.

.label {
    position: absolute;
    font-family: Arial;
    text-align: center;
    white-space: nowrap;
    width: 100%;
    top: 4px;
    left: 0;
}

In the case we have a reached a leaf node, we want to display the label in vertically in the center also.

.node-leaf {
    height: 100%;
    padding: unset;
    transform: translateY(50%);
    top: -6px;
}

Bringing it all together

Let's test what we have so far. We will first need to define a small tree. We will define a helper method in a moment for this, but lets do it by hand this time.

const root = new Node('A');
const A = root.addNode('B');
A.addNode('a1');
A.addNode('a2');
const B = root.addNode('C');
B.addNode('b1');
const b2 = B.addNode('b2');
b2.addNode('c1');
b2.addNode('c2');

If we now plot this with the RecursivePlot class:

> (new RecursivePlot('plot-0')).draw(root);

Because it is quite some work to create the tree by hand, here is a hacked together utility method, that will recursively generate a tree. The input of the method is an list of nodes for that level, e.g. [1, 2, 2, 2] for a binary tree.

const tree = (size) => {
    const __tree = (labels, size, depth) => {
        const __generate = (node, labels, size, depth) => {
            if (depth < 0) {
                return;
            }
            
            for (let i = 0; i < size[depth]; i++) {
                const child = node.addNode(labels[depth] + i);
                __generate(child, labels, size, depth - 1);
            }
        }

        const root = new Node(labels[depth]);
        __generate(root, labels, size, depth - 1);
        return root;
    }

    if (size[0] != 1) {
        console.warn('First node should have size 1. Ignoring size.');
    }
    const labels = [...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'];
    return __tree(
        labels.slice(0, size.length).reverse(), 
        size.reverse(), 
        size.length - 1
    );
}

We can now use tree function to generate a binary tree. Let's see what this looks like.

> (new RecursivePlot('plot1')).draw(tree([1, 2, 2, 2, 2, 2, 2]));

Pretty neat so far! I'm quite happy with the result. Let's see what else we can do with it.

Isometric projection

To get the same effect as in the first illustration, we will project the plot isometrically. Luckily this is quite easy with the following CSS class, that I've found after some googling around.

.isometric {
    transform: rotateX(60deg) rotateY(0deg) rotateZ(-45deg) scale(1.25);
}

We apply the .isometric class to the HTML element of the root node. Note that we will only have to add this class once! We will add an argument isometric to the draw function. If this is set to true, the .isometric class is added to the element of the root node. I've included an example below to show the isometric projection.

HSL color scheme

To add some colors to the plot, we will define a HSL color scheme. This scheme starts from hsl(0, 50%, 80%), and eight steps, where at each step there is an increment of $30$ for the hue. The scheme can be applied to the plot by adding the .scheme-hsl class to the element in which the plot is rendered.

.scheme-hsl > .node {
    background-color: hsl(0, 50%, 80%);
}
.scheme-hsl > * > .node {
    background-color: hsl(30, 50%, 80%);
}
.scheme-hsl > * > * > .node {
    background-color: hsl(60, 50%, 80%);
}
.scheme-hsl > * > * > * > .node {
    background-color: hsl(90, 50%, 80%);
}
.scheme-hsl > * > * > * > * > .node {
    background-color: hsl(120, 50%, 80%);
}
.scheme-hsl > * > * > * > * > * > .node {
    background-color: hsl(150, 50%, 80%);
}
.scheme-hsl > * > * > * > * > * > * > .node {
    background-color: hsl(180, 50%, 80%);
}
.scheme-hsl > * > * > * > * > * > * > * > .node {
    background-color: hsl(210, 50%, 80%);
}

Magma color scheme

The magma color scheme comes from matplotlib, a library for plotting in Python. The scheme can be applied by adding the .scheme-magma class to the element in which the plot is rendered.

.scheme-magma > .node {
    background-color: #310496;
}
.scheme-magma > * > .node {
    background-color: #6D01A7;
}
.scheme-magma > * > * > .node {
    background-color: #9B169E;
}
.scheme-magma > * > * > * > .node {
    background-color: #C03B82;
}
.scheme-magma > * > * > * > * > .node {
    background-color: #DB5C66;
}
.scheme-magma > * > * > * > * > * > .node {
    background-color: #F0814D;
}
.scheme-magma > * > * > * > * > * > * > .node {
    background-color: #FBAE32;
}
.scheme-magma > * > * > * > * > * > * > * > .node {
    background-color: #F7DF23;
}

Sources

The entire source code of this project can be found on my GitHub.