Set Up the Canvas

Set up the HTML for D3 Graphs
Set up the HTML for D3 Graphs

To set up the canvas for D3 graphs, in your HTML file :

  • Line 6: Load D3 directly from — so you don’t need to install it locally
  • Line 7: Load TreeChart.js that we are going to build our D3 graphs in
  • Line 10–12: Style section that we are going to put style code in
  • Line 16: onload= “treeChart()” means we are telling the system to load the treeChart() function in TreeChart.js immediately to show D3 graphs after the page has been loaded
  • Line 18: Create a SVG in the size of 1200px by 1200px for us to put graphic elements in later
  • Line 19: Put in a g element to group all the nested SVG shapes so you can transform them together. In this case, we move all shapes 40 px along the x-axis and 10 px along the y-axis using the translate() function so they are all visible.
  • Line 20: Add two more g elements to group tree links (class=“links”) and tree nodes(class=“node”) respectively. The “links” class needs to be declared before the “node” class so the links appear behind the nodes. You can switch the two lines of code around to see for yourself.

Transform Tabular Data to Hierarchical Data

Now we move on to creating the graphs in TreeChart.js that we linked in the HTML. The most common input data is tabular data. We need to transform it into a hierarchical form to construct a tree chart.

Keep reading line-by-line explanations on how I built this 👉