Day 2: Get the Data

I wanted to build a force layout to represent an org chart. I found an example on Observable. Before digging into the code, we need to prepare the data first. Let’s visualize the characters of four houses in Harry Potter.

I used Excel to prepare the JSON file, from where I copied the nodes and links to a JSON file. The data and other files can be found here. If you upload a new JSON file to the Observable notebook, you will have your own force graph.

Great, it works. Then we will set up the project in a web application.

To set up a project, I like to organize the files in folders. Here is the folder structure:

In the index.html, we need to tell the browser to load the D3 package and our javascript. To get the most recent D3 minified version as a URL link, you can find it at CDNPKG.com.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Get the Data</title>
        <link rel="stylesheet" href="./css/style.css">
        https://unpkg.com/d3@7.8.5/dist/d3.min.js
    </head>
    <body>
        <svg height="600" width="900" id="chart-area"></svg>
        http://./js/main.js
    </body>
</html>

It will run “main.js” in the “js” folder. The “./” refers to the relative path, which means in the same directory as “index.html”.

In our “main.js”, we start with loading the data. In newer examples, you will see async and await. It’s better to use this method to ensure you will get the data before doing something else. async ensures that the function returns a promise – a promise to get the data 🙂

async function drawForce() {
    // read data
    const dataset = await d3.json("./data/harry_potter.json")
    
    const nodes = dataset.nodes
    const links = dataset.links

    console.log(dataset.nodes)
    console.log(dataset.links)

    }
    
    drawForce()

When you open the http-server in the folder, you will see the nodes and links. The data is successfully loaded.

A promise is fulfilled!

Leave a comment